python元组转换成列表_python-将元组列表转换为列表?

python-将元组列表转换为列表?

我如何转换

[(1,), (2,), (3,)]

[1, 2, 3]

fanti asked 2020-06-21T22:26:04Z

11个解决方案

68 votes

使用简单的列表理解:

e = [(1,), (2,), (3,)]

[i[0] for i in e]

会给你:

[1, 2, 3]

Levon answered 2020-06-21T22:26:21Z

55 votes

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

附带说明一下,如果元组中元素的数量可变,则也可以使用itertools中的chain。

>>> 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]

Praveen Gollakota answered 2020-06-21T22:26:46Z

28 votes

如果元组中可以有可变数量的元素,则这是另一种选择:

>>> a = [(1,), (2, 3), (4, 5, 6)]

>>> [x for t in a for x in t]

[1, 2, 3, 4, 5, 6]

这基本上只是以下循环的简化形式:

result = []

for t in a:

for x in t:

result.append(x)

Andrew Clark answered 2020-06-21T22:27:10Z

7 votes

>>> a = [(1,), (2,), (3,)]

>>> zip(*a)[0]

(1, 2, 3)

对于列表:

>>> list(zip(*a)[0])

[1, 2, 3]

fraxel answered 2020-06-21T22:27:30Z

5 votes

您还可以如下使用[1, 2, 3, 4, 5, 6]函数:

e = [(1,), (2,), (3,)]

e_list = list(sum(e, ()))

而且它还可以与列表列表一起使用,以将其转换为单个列表,但是您将需要按以下方式使用它:

e = [[1, 2], [3, 4], [5, 6]]

e_list = list(sum(e, []))

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

Samer Makary answered 2020-06-21T22:27:58Z

4 votes

总有一种方法可以通过... [i[0] for i in e] ... in ...从另一个列表中提取列表。在这种情况下,它将是:

[i[0] for i in e]

Hopfield Sun answered 2020-06-21T22:28:23Z

4 votes

>>> a = [(1,), (2,), (3,)]

>>> b = map(lambda x: x[0], a)

>>> b

[1, 2, 3]

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

b = list(map(lambda x: x[0], a))

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

Touhami answered 2020-06-21T22:28:47Z

3 votes

使用运算符或求和

>>> from functools import reduce ### If python 3

>>> import operator

>>> a = [(1,), (2,), (3,)]

>>> list(reduce(operator.concat, a))

[1, 2, 3]

(要么)

>>> list(sum(a,()))

[1, 2, 3]

>>>

如果在python> 3中,请从functools导入reduce像from functools import reduce

[HTTPS://docs.Python.org/3/library/func tools.HTML#func tools.reduce]

SuperNova answered 2020-06-21T22:29:20Z

2 votes

您还可以在列表理解中解压缩元组:

e = [(1,), (2,), (3,)]

[i for (i,) in e]

仍然会给出:

[1, 2, 3]

mstringer answered 2020-06-21T22:29:44Z

1 votes

一班轮哟!

list(*zip(*[(1,), (2,), (3,)]))

MaK answered 2020-06-21T22:30:04Z

0 votes

在这些情况下,我喜欢这样做:

a = [(1,), (2,), (3,)]

new_a = [element for tup in a for element in tup]

即使您的元组具有多个元素,此方法也有效。 这等效于执行以下操作:

a = [(1,), (2,), (3,)]

new_a = []

for tup in a:

for element in tup:

new_a.append(element)

Daniel Oscar answered 2020-06-21T22:30:28Z

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值