我该如何转换?
[(1,), (2,), (3,)]
Run Code Online (Sandbox Code Playgroud)
至
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
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)
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)
>>> 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)
>>> 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内置函数的最佳解决方案。
您还可以使用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]
| 归档时间: |
|
| 查看次数: |
47119 次 |
| 最近记录: |