只能将list(而不是“int”)连接到lis

2024-09-29 01:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我把我的代码闲置,得到了错误消息

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:]

Tags: 代码消息onlyindex错误notcannum
1条回答
网友
1楼 · 发布于 2024-09-29 01:35:27

试试这个:

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]

相关问题 更多 >