将元组转换为列表

5

我正在尝试将这个元组转换为列表,但是当我运行以下代码时:

mytuple=('7578',), ('6052',), ('8976',), ('9946',)
List=[]
for i in mytuple:
    Start,Mid,End = map(str, mytuple.split("'"))
    List.append(Mid)
print(List)

我收到了这个错误:
AttributeError: 'tuple' object has no attribute 'split'

输出应该是:
[7578, 6052, 8976, 9946]

2
“将元组转换为列表”或“元组转换为字符串”?问题标题与内容不符。 - Austin
2
预期输出是什么? - Dani Mesejo
你是否试图制作一个包含mytuple中元组内部值列表的列表,例如List = [7578,6052,8976,... etc]? - Alex V
@AlejandroAlvarado 是的,我正在尝试制作一个值列表。 - MainStreet
@MainStreet 你想要一个整数列表还是一个字符串列表? - Dani Mesejo
3个回答

9

这正是您正在寻找的内容。

mytuple = (('7578',), ('6052',), ('8976',), ('9946',))
result = [int(x) for x, in mytuple]
print(result)

4
如果我理解正确,这就是你想要的:
mytuple = ('7578',), ('6052',), ('8976',), ('9946',)
result = [e for e, in mytuple]
print(result)

输出

['7578', '6052', '8976', '9946']

问题说输出应该是整数列表,而不是字符串。 - Liam

1
我会使用 itertools.chain.from_iterable(它更倾向于过度冗长而不是过少):
from itertools import chain
result = [int(x) for x in chain.from_iterable(mytuple)]
# vs         ... for x, in mytuple]; the comma is easy to miss

在这两个极端之间会有一个地方

result = [int(x) for x in chain(*mytuple)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接