检查集合中的任何值 [英] Check for any values in set

查看:49
本文介绍了检查集合中的任何值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下设置:

things = {'foo', 'bar', 'baz'}

我想知道集合中是否存在 foo bar.我试过了:

<预><代码>>>>事物中的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屋!

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