定义一个求数值型数据列表中位数的函数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 代码(请注意:不要出现中文)
3条回答 默认 最新
- benbenli 2021-05-17 02:10关注
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!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 软件供应链安全是跟可靠性有关还是跟安全性有关?
- ¥15 电脑蓝屏logfilessrtsrttrail问题
- ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
- ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
- ¥15 Java+vue部署版本反编译
- ¥100 对反编译和ai熟悉的开发者。
- ¥15 带序列特征的多输出预测模型
- ¥15 Python 如何安装 distutils模块
- ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
- ¥15 资源泄露软件闪退怎么解决?