【问题标题】:can only concatenate list (not "int") to list只能将列表(不是“int”)连接到列表
【发布时间】:2019-03-02 21:23:38
【问题描述】:

我将编码放入 IDLE 并收到错误消息

TypeError:只能将列表(不是“int”)连接到列表。

为什么python不接受values[index]中的索引作为int? 这个问题我该怎么办?

def repeat_elem (values, index, num_times):
    # this function returns a new list in which the element of 'values' 
    # at position 'index' has been repeated 'num_times' times
    return values[:index] + values[index]*(num_times - 1) + values[index+1:]

【问题讨论】:

  • values[index] 是一个数字。如果你将它乘以另一个数字,它仍然是一个数字。你需要[values[index]],这是一个由一个数字组成的列表。
  • 你认为values[index]*(num_times - 1)是什么类型的?
  • 您可以使用生成器更优雅地编写它。
  • 为什么你认为index 是问题所在?
  • 如果您还没有,请尝试添加一些调试(查看每个值是否有效,并标记给您问题的那个)我的猜测是 values[index]*(num_times - 1)是问题所在,因为您在 indexnum_times -1 处的值(这是一个 int)无法添加到 values[:index];你想得到:值[(索引num_times-1)]?祝你好运!

标签: python int concatenation


【解决方案1】:

试试这个:

def repeat_elem (values, index, num_times):
    # this function returns a new list in which the element of 'values'
    # at position 'index' has been repeated 'num_times' times
    return values[:index] + ([values[index]] * num_times) + values[index+1:]

在上面的代码中:

  • repeat_elem([1, 2, 3], 0, 5) 返回[1, 1, 1, 1, 1, 2, 3]
  • repeat_elem([1, 2, 3], 1, 5) 返回[1, 2, 2, 2, 2, 2, 3]
  • repeat_elem([1, 2, 3], 2, 5) 返回[1, 2, 3, 3, 3, 3, 3]

【讨论】:

  • () 是多余的,因为* 的优先级高于+
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多