Python Forum
Replace with Maximum Value - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Replace with Maximum Value (/thread-16719.html)



Replace with Maximum Value - leoahum - Mar-11-2019

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!


RE: Replace with Maximum Value - Larz60+ - Mar-11-2019

Quote:replace theirs item
??


RE: Replace with Maximum Value - perfringo - Mar-11-2019

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]]



RE: Replace with Maximum Value - Yoriz - Mar-11-2019

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]]



RE: Replace with Maximum Value - leoahum - Mar-13-2019

(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