更新时间:2023-02-10 15:38:39
您可以使用分片分配和列表理解:
You can use slice assignment and list comprehension:
l = oldlist[:]
l[::2] = [x*2 for x in l[::2]]
您的解决方案是错误的,因为:
Your solution is wrong because:
res
被声明为数字而不是列表multi
res
is declared as a number and not a listmulti
这是您的代码,已更正:
Here's your code, corrected:
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 res
print(multi([12,2,12,2,12,2,12]))