我有一个列表,比如说:list = [6,2,6,2,6,2,6],并且我希望它创建一个新列表,其中每个其他元素乘以2,每个其他元素乘以1(保持不变)。结果应为:[12,2,12,2,12,2,12]。
def multi():
res = 0
for i in lst[0::2]:
return i * 2
print(multi)
Run Code Online (Sandbox Code Playgroud)
也许像这样,但我不知道该如何发展。我的解决方案怎么了?
您可以使用分片分配和列表理解:
l = oldlist[:]
l[::2] = [x*2 for x in l[::2]]
Run Code Online (Sandbox Code Playgroud)
您的解决方案是错误的,因为:
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 res
print(multi([12,2,12,2,12,2,12]))
Run Code Online (Sandbox Code Playgroud)