[英]finding max of list in nested lists
a=[int(i) for i in input().split()]
b=[]
for i in range(a[0]):
x=[int(i) for i in input().split()]
b.append(x)
print(b)
c=[]
for j in range(len(b)):
c.append(max(b[i]))
print(b[0])
print(c)
2
1 3 45 6 8
2 4 56 7
[[1, 3, 45, 6, 8], [2, 4, 56, 7]]
[1, 3, 45, 6, 8]
[56, 56, 56]
我想将每个列表的所有最大元素都放在b到c中。 但我一直在获取整个列表的max元素,而我希望嵌套列表中的每个列表的max为[45,56]
您有一个2D列表,并试图返回该2D列表中每个元素的最大值列表。 遍历2D列表并获取每个元素的最大值:
res = [max(i) for i in nested_list]
另外,您还可以使用map
:
res = list(map(max, nested_list))
您也可以将嵌套列表转换为Pandas Dataframe
并使用max
函数。 这样您就不必担心循环了。
In [350]: import pandas as pd
In [342]: l = [[1, 3, 45, 6, 8], [2, 4, 56, 7]]
In [343]: pd.DataFrame(l)
Out[343]:
0 1 2 3 4
0 1 3 45 6 8.0
1 2 4 56 7 NaN
In [347]: pd.DataFrame(l).max(axis=1).tolist()
Out[347]: [45.0, 56.0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.