如何检查一个变量是否与其他两个变量中的至少一个相同?

如何检查一个变量是否与其他两个变量中的至少一个相同?

问题描述:

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

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)):