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

时间:2022-05-04 14:19:07

This question already has an answer here:

这个问题在这里已有答案:

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?

如何测试变量是否与 - 至少 - 其中一个变量相同?

1 个解决方案

#1


13  

For that use in:

用于以下用途:

if a in (b, c):

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:

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

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

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.

一旦构建完成,对集合中成员资格的测试具有O(1)时间复杂度的平均情况,因此从长远来看它可能更快。

Or, you can also do:

或者,您也可以这样做:

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

#1


13  

For that use in:

用于以下用途:

if a in (b, c):

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:

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

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

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.

一旦构建完成,对集合中成员资格的测试具有O(1)时间复杂度的平均情况,因此从长远来看它可能更快。

Or, you can also do:

或者,您也可以这样做:

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