Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace with Maximum Value
#1
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!
Reply
#2
Quote:replace theirs item
??
Reply
#3
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.
Reply
#4
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]]
Reply
#5
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search & Replace - Newlines Added After Replace dj99 3 3,392 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020