假设我有以下列表:
a = 1
b = [2,3]
c = [4,5,6]
我想将它们连接起来,以便得到以下内容:
[1,2,3,4,5,6]
我尝试了通常的 +
操作员:
>>> a+b+c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
这是因为 a
术语。它只是一个整数。所以我将所有内容转换为列表:
>>> [a]+[b]+[c]
[1, [2, 3], [4, 5, 6]]
不完全是我要找的东西。
我也尝试了 这个答案 中的所有选项,但我得到了同样的 int
上面提到的错误。
>>> l = [a]+[b]+[c]
>>> flat_list = [item for sublist in l for item in sublist]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: 'int' object is not iterable
它应该很简单,但是这个术语没有任何作用 a
。有什么办法可以 有效 地做到这一点?它不一定必须是 pythonic 。
原文由 Ajay H 发布,翻译遵循 CC BY-SA 4.0 许可协议
没有任何东西会自动将
int
视为一个int
的列表。您需要检查该值是否为列表:如果您必须经常这样做,您可能需要编写一个函数:
然后你可以写: