对列表中的每个其他元素进行乘法运算
我有一个列表,比如说: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)
也许可以像这样做,但我不知道该怎么继续。我的解决方案哪里出错了呢?
2 个回答
3
你可以用列表推导和 enumerate
函数来重建这个列表,像这样:
>>> [item * 2 if index % 2 == 0 else item for index, item in enumerate(lst)]
[12, 2, 12, 2, 12, 2, 12]
enumerate
函数会在每次循环中给出当前项的索引和当前项的值。接着,我们使用条件
item * 2 if index % 2 == 0 else item
来决定实际要用的值。在这里,if index % 2 == 0
的意思是如果索引是偶数,就用 item * 2
,否则就直接用 item
本身。
6
你可以使用切片赋值和列表推导式:
l = oldlist[:]
l[::2] = [x*2 for x in l[::2]]
你的解决方案有问题,因为:
- 这个函数没有接收任何参数
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]))