Python 将列表中的其他元素相乘
我有一个列表,比方说:Python 将列表中的其他元素相乘,python,list,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) 也许是这样,但我不知道如何从这开始。我的解决方案怎么会错呢?您可以使用列表理解和枚举函数重构列表,如下所示 >>>
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)
也许是这样,但我不知道如何从这开始。我的解决方案怎么会错呢?您可以使用列表理解和
枚举
函数重构列表,如下所示
>>> [item * 2 if index % 2 == 0 else item for index, item in enumerate(lst)]
[12, 2, 12, 2, 12, 2, 12]
enumerate
函数在每次迭代中给出iterable中项目和当前项目的当前索引。然后我们使用条件
item * 2 if index % 2 == 0 else item
决定要使用的实际值。这里,
如果索引%2==0
则将使用项*2
,否则将按原样使用项
。您可以使用切片分配和列表理解:
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]))