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 c++ word自动化，为什么可用接口是空的？
• ¥15 Matlab计算100000*100000的矩阵运算问题：
• ¥50 VB6.0如何识别粘连的不规则的数字图片验证码
• ¥16 需要完整的这份订单所有的代码，可以加钱
• ¥30 写一个带界面控制的机房电脑一键开机关机并且实时监控的软件
• ¥15 Stata数据分析请教
• ¥15 请教如何为VS2022搭建 Debug|win32的openCV环境?
• ¥15 关于#c++#的问题：c++如何使用websocketpp实现websocket接口调用，求示例代码和相关资料
• ¥15 51单片机的外部中断，按下按键后不能切换到另一个模式