I have two lists:
L1 = [3, 5, 7, 8, 9, 5, 6, 7, 4, 3]
L2 = [1, 4, 5, 8, 3, 6, 9, 3, 5, 9]
And I need to create sub-list for each item in L2 that is smaller than 4, add it to all the numbers in L1 that are smaller than 4. I tried doing this:
result = [(x+y) for x in L2 if x < 4 for y in L1 if y < 4]
But it resulted me this:
[4, 4, 6, 6, 6, 6]
While the outcome should look like this:
[[4, 4], [6, 6], [6, 6]]
any idea on how should I nest it in the right way?
Create a nested list comprehension
>>> [[(x+y) for y in L1 if y < 4] for x in L2 if x < 4]
[[4, 4], [6, 6], [6, 6]]
Here the inner list comprehension creates the inner lists which are then appended to a single list by the outer comprehension.
The numbers below 4 in L1 are:
L1_below_4 = [x for x in L1 if x < 4]
And for L2:
L2_below_4 = [y for y in L2 if y < 4]
Now it's easy:
[[x + y for x in L1_below_4] for y in L2_below_4]
Or as a one-liner:
[[x + y for x in L1 if x < 4] for y in L2 if y < 4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.