开发者

Write conditions based on a list

开发者 https://www.devze.com 2023-01-17 00:55 出处:网络
I\'m writing an if statement in P开发者_如何学运维ython with a lot of OR conditions. Is there an elegant way to do this with a list, within in the condition rather than looping through the list?

I'm writing an if statement in P开发者_如何学运维ython with a lot of OR conditions. Is there an elegant way to do this with a list, within in the condition rather than looping through the list?

In other words, what would be prettier than the following:

if foo == 'a' or foo == 'b' or foo == 'c' or foo == 'd':

I've just taken up Python, and the language has me wanting to write better.


if foo in ('a', 'b', 'c', 'd'):
    #...

I will also note that your answer is wrong for several reasons:

  1. You should remove parentheses.. python does need the outer ones and it takes room.
  2. You're using an assignment operator, not an equality operator (=, not ==)
  3. What you meant to write as foo == 'a' or foo == 'b' or ..., what you wrote wasn't quite correct.


if foo in ("a", "b", "c", "d"):

in, of course, works for most containers. You can check if a string contains a substring ("foo" in "foobar"), or if a dict contains a certain key ("a" in {"a": "b"}), or many things like that.


checking_set = set(("a", "b", "c", "d")) # initialisation; do this once

if foo in checking_set: # when you need it

Advantages: (1) give the set of allowable values a name (2) may be faster if the number of entries is large

Edit some timings in response to "usually much slower" when only "a handful of entries" comment:

>python -mtimeit -s"ctnr=('a','b','c','d')" "'a' in ctnr"
10000000 loops, best of 3: 0.148 usec per loop

>python -mtimeit -s"ctnr=('a','b','c','d')" "'d' in ctnr"
1000000 loops, best of 3: 0.249 usec per loop

>python -mtimeit -s"ctnr=('a','b','c','d')" "'x' in ctnr"
1000000 loops, best of 3: 0.29 usec per loop

>python -mtimeit -s"ctnr=set(('a','b','c','d'))" "'a' in ctnr"
10000000 loops, best of 3: 0.157 usec per loop

>python -mtimeit -s"ctnr=set(('a','b','c','d'))" "'d' in ctnr"
10000000 loops, best of 3: 0.158 usec per loop

>python -mtimeit -s"ctnr=set(('a','b','c','d'))" "'x' in ctnr"
10000000 loops, best of 3: 0.159 usec per loop

(Python 2.7, Windows XP)


>>> foo = 6
>>> my_list = list(range(10))
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print any(foo == x for x in my_list)
True
>>> my_list = list(range(0))
>>>  print any(foo == x for x in my_list)
False

Alternatively:

>>> foo = 6
>>> my_list = set(range(10))
>>> foo in my_list
True
>>> my_list = set(range(0))
>>> foo in my_list
False
0

精彩评论

暂无评论...
验证码 换一张
取 消