检查集合中的任何值 [英] Check for any values in set
问题描述
假设我有以下设置:
things = {'foo', 'bar', 'baz'}
我想知道集合中是否存在 foo
或 bar
.我试过了:
这行得通,但是如果没有多个 or
语句,难道没有更 Pythonic 的方法来进行此检查吗?我在标准的 Python 集合操作中找不到任何可以实现这一点的东西.使用 {'foo', 'bar'} <= things
检查两者,但我想检查它们中的任何一个.
只要你在使用集合,你可以使用:
if {'foo','bar'} &事物:...
&
表示设置指示,交集非空即为真.
Suppose I have the following set:
things = {'foo', 'bar', 'baz'}
I would like to find out if either foo
or bar
exists in the set. I've tried:
>>> 'foo' in things or 'bar' in things
True
This works, but is there not a more Pythonic way of doing this check without having multiple or
statements? I can't find anything in the standard Python set operations that can achieve this. Using {'foo', 'bar'} <= things
checks for both, but I want to check for either of them.
As long as you're using sets, you could use:
if {'foo','bar'} & things:
...
&
indicates set indication, and the intersection will be truthy whenever it is nonempty.
这篇关于检查集合中的任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!