Comparing a string to multiple items in Python

时光怂恿深爱的人放手 提交于 2019-11-26 21:01:39
pillmuncher

If, OTOH, your list of strings is indeed hideously long, use a set:

accepted_strings = {'auth', 'authpriv', 'daemon'}

if facility in accepted_strings:
    do_stuff()

Testing for containment in a set is O(1) on average.

Unless your list of strings gets hideously long, something like this is probably best:

accepted_strings = ['auth', 'authpriv', 'daemon'] # etc etc 

if facility in accepted_strings:
    do_stuff()

To efficiently check if a string matches one of many, use this:

allowed = set(('a', 'b', 'c'))
if foo in allowed:
    bar()

set()s are hashed, unordered collections of items optimized for determining whether a given item is in them.

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