【发布时间】:2017-10-01 21:30:06
【问题描述】:
假设我有以下列表:
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]]
不是我想要的。
我也尝试了this answer 中的所有选项,但我得到了与上述相同的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。
【问题讨论】:
-
问题:为什么一开始就有不一致的数据类型?为什么不对所有变量一致地使用列表?
-
我的问题没这么简单。它是我不断更新列表值的函数的一部分(具有可变长度的列表列表)。如果我把它都写在这里会很乱。但这是基本错误。
标签: python python-3.x list