我正在尝试将此元组转换为列表,但是当我运行此代码时:
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]
答案 0 :(得分:3)
这就是您要寻找的
mytuple = (('7578',), ('6052',), ('8976',), ('9946',))
result = [int(x) for x, in mytuple]
print(result)
答案 1 :(得分:2)
如果我理解正确,那就是你想要的:
mytuple = ('7578',), ('6052',), ('8976',), ('9946',)
result = [e for e, in mytuple]
print(result)
输出
['7578', '6052', '8976', '9946']
答案 2 :(得分:0)
我会使用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)]