将列表中的所有其他元素相乘 [英] Multiply every other element in a list
本文介绍了将列表中的所有其他元素相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,例如:list = [6,2,6,2,6,2,6]
,我希望它创建一个新列表,其中每个其他元素乘以2,每个其他元素乘以1(保持不变).
结果应为:[12,2,12,2,12,2,12]
.
I have a list, let's say: list = [6,2,6,2,6,2,6]
, and I want it to create a new list with every other element multiplied by 2 and every other element multiplied by 1 (stays the same).
The result should be: [12,2,12,2,12,2,12]
.
def multi():
res = 0
for i in lst[0::2]:
return i * 2
print(multi)
也许是这样,但我不知道该如何进行下去.我的解决方案怎么了?
Maybe something like this, but I don't know how to move on from this. How is my solution wrong?
推荐答案
您可以使用分片分配和列表理解:
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
- The function doesn't take any arguments
res
is declared as a number and not a list- Your loop has no way of knowing the index
- You return on the first loop iteration
- 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]))
这篇关于将列表中的所有其他元素相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文