简体   繁体   English

将字符串与Python中的多个项目进行比较

[英]Comparing a string to multiple items in Python

I'm trying to compare a string called facility to multiple possible strings to test if it is valid. 我正在尝试将名为facility的字符串与多个可能的字符串进行比较,以测试它是否有效。 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" ...

If, OTOH, your list of strings is indeed hideously long, use a set: 如果,OTOH,你的字符串列表确实很长,请使用一组:

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

if facility in accepted_strings:
    do_stuff()

Testing for containment in a set is O(1) on average. 集合中的遏制测试平均为O(1)。

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. set() s是经过优化的用于确定给定项是否在其中的项的无序,无序集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM