我把我的代码闲置,得到了错误消息
TypeError: can only concatenate list (not "int") to list.
为什么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:]
试试这个:
在上述代码中:
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]
相关问题 更多 >
编程相关推荐