简体   繁体   中英

How to get multiple element from one using list comprehension in Python?

My title may be not very clear and I apologize, it is not easy to explain. But an example will be more understandable.

a = [1, 4, 7, 10]

b = [x-1, x, x+1 for x in a]

>> expected result: [0,1,2,3,4,5,6,7,8,9,10,11]

Of course, it raises an error.

Is it a way to use list comprehension in order to get this result?

I know I can use b = sum([[x-1, x, x+1] for x in a], []) otherwise, but it is less readable.

You can use two for loops to achieve that:

b = [x+i for x in a for i in (-1,0,1)]

Now b contains:

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

If you want to do this with a list comprehension you need to nest two comprehensions:

>>> b = [ value for x in a for value in (x-1, x, x+1) ]
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Be careful though as once you start nesting comprehensions or including conditions in them they rapidly become unreadable and before you get to that point you should switch over to nested for loops: remember a list comprehension is just a shorthand for the nested loops, it doesn't actually give any performance benefits.

Writing the list comprehension out in 'longhand' looks like this:

b = []
for x in a:
    for value in (x-1, x, x+1):
        b.append(value)

but in actual fact you might be better off just using:

b = []
for x in a:
    b.extend((x-1, x, x+1))

for the same result.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM