Lev*_*von 69

使用简单的列表理解:

e = [(1,), (2,), (3,)]
[i[0] for i in e]
Run Code Online (Sandbox Code Playgroud)

会给你:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


Pra*_*ota 55

@Levon的解决方案非常适合您的情况.

作为旁注,如果元组中有可变数量的元素,您也可以使用chainfrom itertools.

>>> a = [(1, ), (2, 3), (4, 5, 6)]
>>> from itertools import chain
>>> list(chain(a))
[(1,), (2, 3), (4, 5, 6)]
>>> list(chain(*a))
[1, 2, 3, 4, 5, 6]
>>> list(chain.from_iterable(a)) # More efficient version than unpacking
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

  • 还有`chain.from_iterable()`可以为你解包. (12认同)

And*_*ark 28

如果您可以在元组中包含可变数量的元素,那么这是另一种选择:

>>> a = [(1,), (2, 3), (4, 5, 6)]
>>> [x for t in a for x in t]
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

这基本上只是以下循环的缩写形式:

result = []
for t in a:
    for x in t:
        result.append(x)
Run Code Online (Sandbox Code Playgroud)

  • 迄今为止的最佳答案,简洁/概括。但语法相当令人费解。最后一个“for”语句是否类似于列表理解中的尾随“if”语句,例如“[i for i in range(10) if i%2==0]”?我对后者很熟悉。 (2认同)

fra*_*xel 7

>>> a = [(1,), (2,), (3,)]
>>> zip(*a)[0]
(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

列表:

>>> list(zip(*a)[0])
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

  • 我对它也比较熟悉和熟悉,但我正在尝试更多地了解zip和itertools,所以这很有启发性:) (2认同)

Tou*_*ami 7

>>> a = [(1,), (2,), (3,)]
>>> b = map(lambda x: x[0], a)
>>> b
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

使用python3,你必须将list(..)函数放到map(..)的输出中,即

b = list(map(lambda x: x[0], a))
Run Code Online (Sandbox Code Playgroud)

这是使用 python内置函数的最佳解决方案。


Sam*_*ary 5

您还可以使用sum如下功能:

e = [(1,), (2,), (3,)] 
e_list = list(sum(e, ()))
Run Code Online (Sandbox Code Playgroud)

它也可以使用列表列表将其转换为单个列表,但您需要按如下方式使用它:

e = [[1, 2], [3, 4], [5, 6]]
e_list = list(sum(e, []))
Run Code Online (Sandbox Code Playgroud)

这会给你 [1, 2, 3, 4, 5, 6]