Python 只能将列表(而不是“int”连接到列表

Python 只能将列表(而不是“int”连接到列表,python,int,concatenation,Python,Int,Concatenation,我把代码放在空闲状态,收到了错误消息 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 r

我把代码放在空闲状态,收到了错误消息

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:]
试试这个:

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:]
在上述代码中:

  • 重复元素([1,2,3],0,5)
    返回
    [1,1,1,1,2,3]
  • 重复元素([1,2,3],1,5)
    返回
    [1,2,2,2,3]
  • 重复元素([1,2,3],2,5)
    返回
    [1,2,3,3,3]

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