Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking up an item from a list of lists

Tags:

python

list

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)

like image 952
Macsim Avatar asked Nov 24 '15 19:11

Macsim


People also ask

What is a nested list?

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).

Can you have a list within a list in Python?

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.


2 Answers

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]]
like image 106
Bhargav Rao Avatar answered Oct 16 '22 00:10

Bhargav Rao


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.

like image 36
Josh Weinstein Avatar answered Oct 16 '22 00:10

Josh Weinstein