How to check if a variable is the same as at least one of two other variables? [duplicate]

独自空忆成欢 提交于 2019-12-01 06:13:46

问题


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:


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:

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.

Or, you can also do:

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


来源:https://stackoverflow.com/questions/23496860/how-to-check-if-a-variable-is-the-same-as-at-least-one-of-two-other-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!