简体   繁体   English

Python列表理解,解包和多个操作

[英]Python list comprehension, unpacking and multiple operations

I want to unpack the tuples I create by doing the following so he the result is just one simple list. 我想通过执行以下操作来解压缩我创建的元组,因此结果只是一个简单的列表。 I can get the desired result in 2-3 lines but surely there is a oneliner list.comp? 我可以在2-3行中获得所需的结果但肯定有一个oneliner list.comp?

x = range(10)
y = [(i,j**2) for i,j in zip(x,x)]
>>>y
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9
, 81)]
>>>

What I want is result = [0,0,1,1,2,4,3,9.....] 我想要的是result = [0,0,1,1,2,4,3,9.....]

Doing

y = len(x)*[0]
y[::2] = x
y[1::2] = [i**2 for i in x]

Gives what I want but what if I need the more general case: 给出我想要的但是如果我需要更一般的情况怎么办:

y = [(i, sqrt(i), i**3, some_operation_on_i, f(i), g(i)) for i in x]

Eg I should be able to get a straight list like result where I only specified one operation (square) to follow each i but now with an arbitrary number of operations following each i. 例如,我应该能够得到一个像结果一样的直接列表,其中我只指定了一个操作(正方形)来跟随每个i但现在每个i之后有任意数量的操作。

Use a nested list comprehension: 使用嵌套列表理解:

result = [a for tup in y for a in tup]

Example: 例:

>>> x = range(10)
>>> y = [(i,j**2) for i,j in zip(x,x)]
>>> [a for tup in y for a in tup]
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]

This will work fine for your more general case as well, or you could do it all in one step: 这对于更一般的情况也适用,或者您可以一步完成所有操作:

y = [a for i in x for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i))]

In case the nested list comprehensions look odd, here is how this would look as a normal for loop: 如果嵌套列表内涵看起来很奇怪,这里是如何做到这一点看起来像一个正常for循环:

y = []
for i in x:
    for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i)):
        y.append(a)
>>> import itertools
>>> list(itertools.chain.from_iterable(y))
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]

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

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