[Solved] Iterating through a list or a list of lists and replacing specific elements in the list of lists [closed]


b = max(a)
[1 if x==b else 0 for x in a]

max(a) will return the maximum element in your list

so you want to essentially replace all non-max values with 0 and all max values to 1.

You can do this several ways but the above seems most to the point.

Basically this is short hand for looping through each element, a different way to write this out, replacing elements in a would be:

b=max(a)
for n, i in enumerate(a):
  if i == b:
    a[n]=1
  else:
    a[n]=0

For Example2, just do the same thing for each list in c:

[([1 if x ==max(i) else 0 for x in i] for i in c]

5

solved Iterating through a list or a list of lists and replacing specific elements in the list of lists [closed]