I'm pretty new in python and have am difficulty doing the next assignment. I am receiving a list of lists with numbers and the word none, for example:
[[1,None],[2,4],[1.5,2]]
My problem is when I go through None (I need to sum up the lists) I need to replace it by the max number in the same place in the other lists.
So my result should be None = max(4,2)
and receive :
[[1,4],[2,4],[1.5,2]]
If I go through a for loop I don't understand how can I go to the other sub lists and check them out (especially when I don't know how many subs lists I have)
A nested list is simply a list that occurs as an element of another list (which may of course itself be an element of another list, etc.). Common reasons nested lists arise are: They're matrices (a list of rows, where each row is itself a list, or a list of columns where each column is itself a list).
Lists are useful data structures commonly used in Python programming. A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.
Use a nested list comprehension with conditional
>>> l = [[1,None],[2,4],[1.5,2]]
>>> def findMax(j):
... return max(i[j] for i in l)
...
>>> [[j if j is not None else findMax(k) for k,j in enumerate(i)] for i in l]
[[1, 4], [2, 4], [1.5, 2]]
Here the list comprehension checks if each element is None or not. If not it will print the number, else it will fnd the maximum and print that element.
Another way using map
is
>>> l = [[1,None],[2,4],[1.5,2]]
>>> maxVal = max(map(max, l))
>>> [[j if j is not None else maxVal for k,j in enumerate(i)] for i in l]
[[1, 4], [2, 4], [1.5, 2]]
Here is a hint: In Python, a for in loop iterates through all the elements in some iterable. If you have a list of lists, that means each element in the list can also have a for loop applied to it, as in a for loop inside a for loop. You could use this if and only if the maximum depth of a list is 2:
def get_deep_max(deeplst):
new = []
for elem in deeplst:
for num in elem:
new.append(num)
return max(new)
Try writing the code for replacing the none value yourself for practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With