简体   繁体   中英

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]

i want to put all the max elements of each list in b to c. but i keep getting the max element of the whole list, while i want max of each list in nested lists which is [45,56]

You have a 2D list and are trying to return a list of the maxes for each element in that 2D list. Iterate over the 2D list and take the max for each element:

res = [max(i) for i in nested_list]

Additionally you can also use map :

res = list(map(max, nested_list))

You can use a list comprehension that takes the max for each sub-list l :

b = [[1, 3, 45, 6, 8], [2, 4, 56, 7]]
c = [max(l) for l in b]

print(c)

Output

[45, 56]

The above list comprehension is equivalent to the following for loop:

c = []
for l in b:
    c.append(max(l))

You can also convert your nested list to Pandas Dataframe and use max function. You won't have to worry about loops then.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM