Posts: 39
Threads: 14
Joined: Oct 2018
List = [[0,1,2],[4,5,6,7],[7,8,9,10]]
def ReplacewithMax (l, count = 0, L = None):
if count == 0:
L = []
K = []
for i in l[count]:
K.append(max(l[count]))
L.append(K)
count += 1
return ReplacewithMax(l,count,L)
if count < len(l):
K = []
for i in l[count]:
K.append(max(l[count]))
L.append(K)
count += 1
return ReplacewithMax(l,count,L)
if count == len(l):
return L
K = ReplacewithMax(List)
print (K) I have a nested list. In the second level, I want to replace theirs item with the maximum value in each list. The code I post achieved the goal. But I'm seeking for a simpler way to do that.
Thanks!
Posts: 12,032
Threads: 486
Joined: Sep 2016
Quote:replace theirs item
??
Posts: 1,950
Threads: 8
Joined: Jun 2018
Maybe something like this:
>>> List = [[0,1,2],[4,5,6,7],[7,8,9,10]]
>>> [[max(row) for el in row] for row in List]
[[2, 2, 2], [7, 7, 7, 7], [10, 10, 10, 10]]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Posts: 2,168
Threads: 35
Joined: Sep 2016
Another
my_list = [[0,1,2],[4,5,6,7],[7,8,9,10]]
new_list = [[max(each)]*len(each) for each in my_list]
print(new_list) Output: [[2, 2, 2], [7, 7, 7, 7], [10, 10, 10, 10]]
Posts: 39
Threads: 14
Joined: Oct 2018
(Mar-11-2019, 09:12 PM)Yoriz Wrote: Another
my_list = [[0,1,2],[4,5,6,7],[7,8,9,10]]
new_list = [[max(each)]*len(each) for each in my_list]
print(new_list) Output: [[2, 2, 2], [7, 7, 7, 7], [10, 10, 10, 10]]
Thanks, that is very helpful
|