如何检查一个变量是否与其他两个变量中的至少一个相同? [英] How to check if a variable is the same as at least one of two other variables?

查看:80
本文介绍了如何检查一个变量是否与其他两个变量中的至少一个相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,想检查它是否至少与其他两个变量之一匹配。

I have a variable, and want to check if it matches at least one of the other two variables.

很明显,我可以这样做:

Clearly I can do:

if a == b or a == c:

但是我想知道是否还有更短的方法,例如:

But I want to know if there is any shorter way, something like:

if a == (b or c):

如何测试变量是否与-至少-

How to test if a variable is the same as - at least - one of the others?

推荐答案

为此,请在中使用

For that use in:

if a in (b, c):

元组中进行成员资格测试的平均情况为 O(n)时间复杂度。如果您有大量的值并且正在对同一值执行许多成员资格测试,则可能值得创建一个 set 来提高速度:

Testing for membership in a tuple has an average case of O(n) time complexity. If you have a large collection of values and are performing many membership tests on the same collection of values, it may be worth creating a set for speed:

x = set((b,c,d,e,f,g,h,i,j,k,l,...))
if a in x:
    ...
if y in x:
    ...    

构造完成后,测试集中的成员资格的平均情况为 O(1 )时间复杂度,因此从长远来看可能会更快。

Once it has been constructed, testing for membership in the set has an average case of O(1) time complexity, so it is potentially faster in the long run.

或者,您也可以这样做:

Or, you can also do:

if any(a == i for i in (b,c)):

这篇关于如何检查一个变量是否与其他两个变量中的至少一个相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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