List 只能将列表(而不是“str”)连接到列表

List 只能将列表(而不是“str”)连接到列表,list,python-2.7,for-loop,integer,List,Python 2.7,For Loop,Integer,我编写了以下代码片段: 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 yiel

我编写了以下代码片段:

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],它基本上是创建一个包含一个项目的列表

通常,您也可以将+用于字符串,但是您想要连接的每个项目都需要是字符串。因此,如果您有两个列表,并且希望向其中添加任何项目,则需要将该项目转换为列表。

append、[]+[]等。