python - 使用 if 语句列出理解

标签 python if-statement list-comprehension

我想比较两个可迭代对象并打印出现在两个可迭代对象中的项目。

>>> 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函数有什么问题?

最佳答案

你的顺序错了。 if 应该在 for 之后(除非它在 ​​if-else 三元运算符中)

[y for y in a if y not in b]

但是这会起作用:

[y if y not in b else other_value for y in a]

关于python - 使用 if 语句列出理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474933/

相关文章:

javascript - 检查 IF 语句内的函数解释

python - 具有两个 "fors"和一个 "if"条件的列表理解

python - 尝试在 conda 中离线安装包时出现错误消息

audio - arduino tone命令问题

python - 用于启动 test_train_split 的数组切片符号?

java - Do-While 循环错误 - 不重复玩游戏

python - 压缩多个列表推导

haskell 错误 "parse error on input ‘if'“

python - BeautifulSoup 刮 table 与 table 休息

python - 向图像添加新 channel