Python列表理解-简单 [英] Python list comprehension - simple
本文介绍了Python列表理解-简单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,我只想在满足特定条件的条目上使用某些功能,而其他条目保持不变.
I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified.
示例:假设我只想将偶数个元素乘以2.
Example: Say I want to multiply by 2 only those elements who are even.
a_list = [1, 2, 3, 4, 5]
想要的结果:
a_list => [1, 4, 3, 8, 5]
但是[elem * 2 for elem in a_list if elem %2 == 0]
会产生[4, 8]
(它还充当过滤器).
But [elem * 2 for elem in a_list if elem %2 == 0]
yields [4, 8]
(it acted as a filter in addition).
正确的解决方法是什么?
What is the correct way to go about it?
推荐答案
使用条件表达式:
[x * 2 if x % 2 == 0 else x
for x in a_list]
(数学怪人的注:您也可以通过以下方式解决这种特殊情况
(Math geek's note: you can also solve this particular case with
[x * (2 - x % 2) for x in a_list]
但是无论如何我还是希望第一个选项;)
but I'd prefer the first option anyway ;)
这篇关于Python列表理解-简单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文