Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension list of lists

I have a list of lists, and would like to use list comprehension to apply a function to each element in the list of lists, but when I do this, I end up with one long list rather than my list of lists.

So, I have

x = [[1,2,3],[4,5,6],[7,8,9]]
[number+1 for group in x for number in group]
[2, 3, 4, 5, 6, 7, 8, 9, 10]

But I want to get

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]

How do I go about doing this?

like image 456
Jean-Luc Avatar asked Feb 02 '14 05:02

Jean-Luc


People also ask

How do you flatten a list of lists with a list comprehension?

To flatten a list of lists, use the list comprehension statement [x for l in lst for x in l] . To modify all elements in a list of lists (e.g., increment them by one), use a list comprehension of list comprehensions [[x+1 for x in l] for l in lst] .

Can list comprehension be nested?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.

What is the difference between list and list comprehension?

Difference between list comprehension and for loop. The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code.

Does list comprehension create a new list?

List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.


2 Answers

Use this:

[[number+1 for number in group] for group in x] 

Or use this if you know map:

[map(lambda x:x+1 ,group) for group in x] 
like image 59
Booster Avatar answered Sep 17 '22 21:09

Booster


Starting from the structure of your data:

x = [[1,2,3],[4,5,6],[7,8,9]]

Every group is a triplet [a,b,c], so I consider for readability a solution like:

«take every group [a,b,c] from the list and provide me the list of [a+1,b+1,c+1] »

x_increased = [ [a+1,b+1,c+1] for [a,b,c] in x ]

like image 28
dodo Avatar answered Sep 17 '22 21:09

dodo