您可以使用分片分配和列表理解:
l = oldlist[:]l[::2] = [x*2 for x in l[::2]]
您的解决方案是错误的,因为:
- 该函数不带任何参数
res
被声明为数字而不是列表- 您的循环无法知道索引
- 您在第一次循环迭代中返回
- 与功能无关,但您实际上并未调用
multi
这是您的代码,已更正:
def multi(lst): res = list(lst) # Copy the list # Iterate through the indexes instead of the elements for i in range(len(res)): if i % 2 == 0: res[i] = res[i]*2 return resprint(multi([12,2,12,2,12,2,12]))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)