如何在python中的map()on list中使用lambda if else?

2024-09-02 03:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单['apple', 'banana', 'cherry']

我想在上面运行map,它会选择一些项目

l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])

它似乎应该工作,但它给出的语法错误

这里的问题是什么


Tags: 项目lambdamapappleifpasselsebanana
3条回答

你需要这个:

[x for x in ['apple', 'banana', 'cherry'] if x == "apple"]

您可能需要在此处使用filter并使用lambda x : x == "apple"

Ex:

l = list(filter(lambda x : x == "apple", ['apple', 'banana', 'cherry']))
print(l)

pass不是值,因此不能在表达式中使用它。您可以使用None,但最终得到的是['apple', None, None],而不仅仅是['apple'],因此您必须像这样过滤None

l = filter(lambda x: x is not None, map(lambda x : x if x == "apple" else None, ['apple', 'banana', 'cherry']))

更干净的解决方案是使用列表理解:

l = [ x for x in ['apple', 'banana', 'cherry'] if x == 'apple' ]

相关问题 更多 >