Comparing a string to multiple items in Python

女生的网名这么多〃 提交于 2019-11-26 06:45:59

问题


I\'m trying to compare a string called facility to multiple possible strings to test if it is valid. The valid strings are:

auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7

Is there an efficient way of doing this other than:

if facility == \"auth\" or facility == \"authpriv\" ...

回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/6838238/comparing-a-string-to-multiple-items-in-python

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