只能将列表(不是 "str")连接到列表

Can only concatenate list (not "str") to list

我写了下面的代码片段:

origilist = [6, 252, 13, 10]
decilist = list(xrange(256))


def yielding(decilist, origilist):
    half_origi = (len(origilist)/2)
    for n in decilist:
        yield origilist[:half_origi] + n + origilist[half_origi:]


for item in yielding(decilist, origilist):
    print item

当我 运行 我得到的代码:

    yield origilist[:half_origi] + n + origilist[half_origi:]
TypeError: can only concatenate list (not "int") to list

是否可以在特定索引中将整数连接到另一个列表?

感谢您的回答

尝试:

yield origilist[:half_origi] + [n] + origilist[half_origi:]

[n] 是一个列表,其中一个元素可以连接到其他列表)。

您只能连接列表,n 是列表中的项目,而不是列表中的项目。如果你想将它与列表连接起来,你需要使用 [n],这基本上是创建一个包含一项的列表。

一般来说,您也可以对字符串使用 +,但是 每个 您想要连接的项目都需要是字符串。因此,如果您有两个列表并想向其中添加任何项目,则需要将该项目转换为列表。