【问题标题】:List += Tuple vs List = List + Tuple列表 += 元组与列表 = 列表 + 元组
【发布时间】:2012-10-31 05:50:42
【问题描述】:

假设我有这些任务:

points = []
point = (1, 2)

我怎么会这样做:

points += point

它工作得很好,并且给了我积分 = [1, 2]。 但是,如果我这样做:

points = points + point

它给了我一个 TypeError: can only concatenate list (not "tuple") to list。 不过,这些陈述不是一回事吗?

【问题讨论】:

    标签: python list concatenation tuples


    【解决方案1】:

    不同之处在于list += 等价于list.extend(),它接受任何可迭代并扩展列表,它作为一个元组是一个可迭代的。 (并就地扩展列表)。

    另一方面,第二个将一个新列表分配给points,并尝试将一个列表连接到一个元组,但由于不清楚预期结果是什么(列表还是元组?),所以没有完成。

    【讨论】:

      猜你喜欢
      • 2012-07-26
      • 2014-04-27
      • 2014-09-17
      • 2018-04-15
      • 2021-08-15
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多