List comprehension on a nested list? List comprehension on a nested list? python python

List comprehension on a nested list?


Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].


Here is how to convert nested for loop to nested list comprehension:

enter image description here

Here is how nested list comprehension works:

            l a b c d e f            ↓ ↓ ↓ ↓ ↓ ↓ ↓In [1]: l = [ [ [ [ [ [ 1 ] ] ] ] ] ]In [2]: for a in l:   ...:     for b in a:   ...:         for c in b:   ...:             for d in c:   ...:                 for e in d:   ...:                     for f in e:   ...:                         print(float(f))   ...:                         1.0In [3]: [float(f)         for a in l   ...:     for b in a   ...:         for c in b   ...:             for d in c   ...:                 for e in d   ...:                     for f in e]Out[3]: [1.0]

For your case, it will be something like this.

In [4]: new_list = [float(y) for x in l for y in x]


>>> l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]>>> new_list = [float(x) for xs in l for x in xs]>>> new_list[40.0, 20.0, 10.0, 30.0, 20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0, 30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0]


matomo