使用 if 语句进行列表理解 [英] List comprehension with if statement

查看:28
本文介绍了使用 if 语句进行列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>a = ('q', 'r')>>>b = ('q')# 迭代a.如果 y 不在 b 中,则打印 y.# 我想看到 ['r'] 打印出来.>>>打印([ y 如果 y 不在 b 中,则 y 在 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]

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])
                              ^

But it gives me a invalid syntax error where the ^ has been placed. What is wrong about this lamba function?

解决方案

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]

This would work however:

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

这篇关于使用 if 语句进行列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆