Skip to main content
 首页 » 编程设计

python之如何对依赖于先前元素的列表元素执行操作

2025年05月04日1452php

使用map可以对list中的当前元素进行操作:

l = [1,2,3,4,5,6]; 
 
 
print(list(map(lambda x: x*2, l)))   
# gives [2, 4, 6, 8, 10, 12] 

在上面,对 l 中的所有元素都乘以 2。但是,只有当 l 中的前一个值是奇数时,如何将 l 中的一个元素乘以 2?可以为此使用 map 吗?

例如获取:

[1,4,3,8,5,12] % only 2, 4 and 6 from l are multiplyied by 2, because before them there are odd numbers 1,3,5.  

请您参考如下方法:

如果你在 enumerated 版本上做,你可以使用 map:

print(list(map(lambda index,x: x*2 if index > 1 and l[index-1] & 1 else x, enumerate(l)))) 

但是,正如您可能已经注意到的那样,这确实不是很可读。最好只使用列表理解或 for 循环:

print([x*2 if index > 1 and l[index-1] & 1 else x 
       for index, x in enumerate(l)])