定义一个求数值型数据列表中位数的函数median(lst),参数为一个包含若干个数值型数据的简单列表,函数返回中位数的值。 image.png 主程序首先通过input 以嵌套列表形式输入一个m*m的整数矩阵,如 [ [1,12,3,-2] , [14,5,26,9] , [18,9,10,-7] , [61,112,13,-12] ],然后调用自定义median函数循环求解每行数据的中位数,生成一个含有m个元素的中位数列表。最后输出中位数列表的中位数,以及中位数列表中的所有整数元素(即 小数部分为0的元素)组成的列表(循环中使用匿名函数实现,参照课本131页内容) 输入描述 [[1,7,4,6],[5,9,4,2],[88,3,3,1],[88,31,12,1]] 输出描述 The median of medians is 4.75 and The list of integer median is [5.0, 3.0] 样例输入1: [[1,7,4,6],[5,9,4,2],[88,3,3,1],[88,31,12,1]] 样例输出1: The median of medians is 4.75 and The list of integer median is [5, 3] 样例输入2: [[11,2,13],[22,1,12]] 样例输出2: The length of sub_list must be same to main_list! Please check your input ! 语言 Python 代码(请注意:不要出现中文)
s=input("Please enter m * m matrix in the form of list of list of integers in a line: ")
#s = "[ [1,12,3,-2] , [14,5,26,9] , [18,9,10,-7] , [61,112,13,-12] ]"
#s = " [[1,7,4,6],[5,9,4,2],[88,3,3,1],[88,31,12,1]] "
def textToList(t):
ta = t.replace(" ", "").split( "],[")
taa = [x.replace("[","").replace("]","").split(",") for x in ta]
iaa =[[int(y) for y in x] for x in taa]
return iaa
def calc_median(lst):
lst.sort()
l = len(lst)
if l % 2 == 0:
return (lst[int(l/2) - 1] + lst[int(l/2)]) / 2
else:
return lst[int(len(l) / 2)]
lst = textToList(s)
m = len(lst)
valid = True
medians = []
for i in range(0, m):
l = lst[i]
if (len(l) != m):
print(f"The length of sub_list {i} is {l} but it must be same to main_list {m}! Please check your input!")
valid = False
break
medians.append(calc_median(l))
if valid:
mi = [x for x in medians if int(x) == x]
mm = calc_median(medians)
print(f"The median of medians is {mm} and The list of integer median is {mi}")
# Output
Please enter m * m matrix in the form of list of list of integers in a line: [ [1,12,3,-2] , [14,5,26,9] , [18,9,10,-7] , [61,112,13,-12] ]
The median of medians is 10.5 and The list of integer median is [2.0, 37.0]
Please enter m * m matrix in the form of list of list of integers in a line: [[1,7,4,6],[5,9,4,2],[88,3,3,1],[88,31,12,1]]
The median of medians is 4.75 and The list of integer median is [5.0, 3.0]
Please enter m * m matrix in the form of list of list of integers in a line: [[11,2,13],[22,1,12]]
[[11,2,13],[22,1,12]]
The length of sub_list 0 is [11, 2, 13] but it must be same to main_list 2! Please check your input!
题目好长,这是要直接求代码,害
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632