m0_58318154 2021-05-16 22:12 采纳率: 75%

# 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 资源泄露软件闪退怎么解决？