且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间: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:

  1. 该函数不接受任何参数
  2. res被声明为数字而不是列表
  3. 您的循环无法知道索引
  4. 您在第一次循环迭代中返回
  5. 与该功能无关,但您实际上并未调用multi
  1. The function doesn't take any arguments
  2. res is declared as a number and not a list
  3. Your loop has no way of knowing the index
  4. You return on the first loop iteration
  5. Not related to the function, but you didn't actually call multi

这是您的代码,已更正:

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]))