让我们说例如,人们想要遍历包含相同数量项目的3个列表。我如何比较相同索引的项目并将其中位数放在名为中位列表的新列表中?
example output:
list_1 = [1,2,3]
list_2 = [1,3,5]
list_3 = [2,4,6]
median_list = [1, 3, 5]
答案 0 :(得分:2)
>>> list_1 = [1,2,3]
>>> list_2 = [1,3,5]
>>> list_3 = [2,4,6]
>>> zip(list_1, list_2, list_3) # To make 1st items pair, 2nd items pairs, ...
[(1, 1, 2), (2, 3, 4), (3, 5, 6)]
>>> [sorted(xs)[1] for xs in zip(list_1, list_2, list_3)]
[1, 3, 5]
如果您使用的是Python 3.4+,则可以使用statistics.median
:
>>> [statistics.median(xs) for xs in zip(list_1, list_2, list_3)]
[1, 3, 5]