将列表中的所有其他元素相乘

ras*_*eme 0 python list

我有一个列表,比如说: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)

也许像这样,但我不知道该如何发展。我的解决方案怎么了?

par*_*ent 6

您可以使用分片分配和列表理解:

l = oldlist[:]
l[::2] = [x*2 for x in l[::2]]
Run Code Online (Sandbox Code Playgroud)

您的解决方案是错误的,因为:

  1. 该函数不带任何参数
  2. res 被声明为数字而不是列表
  3. 您的循环无法知道索引
  4. 您在第一次循环迭代中返回
  5. 与功能无关,但您实际上并未调用 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)