我有一个元组列表,其中一个元素是列表。
example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
我希望最终只得到一个元组列表。
output = [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
这个问题似乎解决了元组的问题,但我很担心因为我的用例在内部列表中有更多的元素。
[(a, b, c, d, e) for [a, b, c], d, e in example]
看起来很繁琐。有更好的写法吗?
我有一个元组列表,其中一个元素是列表。
example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
output = [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
这个问题似乎解决了元组的问题,但我很担心因为我的用例在内部列表中有更多的元素。
[(a, b, c, d, e) for [a, b, c], d, e in example]
看起来很繁琐。有更好的写法吗?
+
进行连接。因此,您可以执行以下操作:>>> example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
>>> [tuple(x[0]) + x[1:] for x in example]
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
[tuple(i+j) for i, *j in x]
*j
的SyntaxError: invalid syntax
错误。 - wflynnyfrom itertools import chain
def to_iterable(x):
try:
return iter(x)
except TypeError:
return x,
example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
output = [tuple(chain(*map(to_iterable, item))) for item in example]
这将会得到:
print(output)
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
这种方法比其他解决方案更冗长,但具有一个很好的优点:无论内部元组中列表的位置或数量如何,都可以正常工作。根据您的要求,这可能是过度设计或是一个好的解决方案。
([a, b, c], d, e)
模式? - ereOn