简体   繁体   English

如何在Python中使用list comprehension从一个元素中获取多个元素?

[英]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. 我知道我可以使用b = sum([[x-1, x, x+1] for x in a], [])否则,它的可读性较差。

You can use two for loops to achieve that: 您可以使用两个for循环来实现:

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

Now b contains: 现在b包含:

[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. 但是要小心,因为一旦你开始嵌套理解或包含条件,它们很快变得不可读,在你到达那一点之前你应该切换到嵌套for循环:记住列表理解只是嵌套循环的简写,它没有'实际上给予任何性能上的好处。

Writing the list comprehension out in 'longhand' looks like this: 用'longhand'编写列表解析看起来像这样:

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. 为了相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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