【问题标题】:Can only concatenate list (not "str") to list只能将列表(不是“str”)连接到列表
【发布时间】:2015-07-15 01:47:19
【问题描述】:

我写了如下代码sn-p:

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

有没有在特定索引中将整数连接到另一个列表?

感谢您的回答

【问题讨论】:

  • append[]+[]

标签: list python-2.7 for-loop integer


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2020-06-02
      相关资源
      最近更新 更多