使用if语句列出理解 [英] List comprehension with if statement
本文介绍了使用if语句列出理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较2个iterables并打印两个iterables中出现的项目。
I want to compare 2 iterables and print the items which appear in both iterables.
>>> a = ('q', 'r')
>>> b = ('q')
# Iterate over a. If y not in b, print y.
# I want to see ['r'] printed.
>>> print([ y if y not in b for y in a])
^
但是它给了我一个无效的语法错误,其中放置了 ^
。
这个lamba函数有什么问题?
But it gives me a invalid syntax error where the ^
has been placed.
What is wrong about this lamba function?
推荐答案
你的订单错了。 如果
应该在之后
(除非它在 if-else
三元运算符)
You got the order wrong. The if
should be after the for
(unless it is in an if-else
ternary operator)
[y for y in a if y not in b]
但这可行:
[y if y not in b else other_value for y in a]
这篇关于使用if语句列出理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文