Reputation: 79
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]
Upvotes: 0
Views: 149
Reputation: 34046
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]
Upvotes: 0
Reputation: 13498
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))
Upvotes: 2
Reputation: 61900
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))
Upvotes: 0