如何将整数组合成列表



我在Codecademy做一个问题,它是:

  1. 创建一个名为double_index的函数。两个参数:名为lst的列表和名为index的单个数字。

  2. 函数返回一个新列表,其中除了索引处的元素外,所有元素都与lst中的相同。索引处的元素应为原始lst的索引处元素值的两倍

  3. 如果索引不是有效的索引,则函数应返回原始列表。

我的代码是:

def double_index(lst, index):
if index <= len(lst) and index >0:
double_value = lst[index]*2
new_lst = lst[:index] + list(double_value) + lst[index+1:]
return new_lst
else:
return lst

然而,当我运行代码时,错误发生在第4行,因为double_value,"int不可迭代"。

我用错了list((函数了吗?还是这里有一些概念上的错误?

list需要一个可迭代的对象,因此它不能与数字一起使用。

当您需要单个项目列表时,只需使用[value]即可。

您可以通过索引来切换指定元素的值

if index <= len(lst) and index >0:
lst[index] *= 2
return lst
else:
return lst

最新更新