【问题标题】:"TypeError: can only concatenate list (not "int") to list" What have I done wrong?“TypeError:只能将列表(而不是“int”)连接到列表“我做错了什么?
【发布时间】:2018-09-04 01:38:01
【问题描述】:
def ifWin2(el):
    el2, el3 = el[2],el[3]
    if el2 > el3:
        el2 = el2 + 3000
        el3 = el3 + 50
    elif el2 < el3:
        el2 = el2 + 50
        el3 = el3 + 3500
    else:
        el2 = el2 + 1000
        el3 = el3 + 1000

上面的代码给了我 TypeError,说它“只能将列表(而不是“int”)连接到列表”(我知道)。但是,我确信 el2 和 el3 都不是多维列表。为什么我会收到此错误?

【问题讨论】:

  • el2el3 长什么样子?
  • 当然,el2el3 都不是多维列表,但 3000 根本不是列表。你正在做的正是错误所说的你正在做的事情。如果您想就地变异,请致电el2.append(3000),如果您想复制,请致电el2 = el2 + [3000]
  • 或者直接使用el2 += [3000]@abarnert。
  • @ChristianDean 当然,但这里没有真正好的理由这样做,我认为这只会让他混淆 += 对可变类型和不可变类型所做的区别。

标签: python


【解决方案1】:

似乎您正在尝试将常量添加到列表中。在这种情况下,您应该使用 Numpy 数组:

Sum one number to every element in a list (or array) in Python

【讨论】:

    【解决方案2】:
    el2 = el2 + 3000
    

    el2 可能是一个单维列表,但3000 根本不是一个列表,它只是一个int。因此错误消息:

    TypeError: can only concatenate list (not ”int“) to list”
    

    如果要连接包含3000 的单元素列表,则拼写为[3000]

    el2 = el2 + [3000]
    

    但是,除非您出于某种原因需要避免更改原始列表,否则您可能只想append 对其进行修改:

    el2.append(3000)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多