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

2024-06-06 18:55:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个名为facility的字符串与多个可能的字符串进行比较,以测试它是否有效。有效字符串为:

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

有没有一种有效的方法可以做到这一点,除了:

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

Tags: 字符串authftpmaildaemoncronnewssyslog
3条回答

如果,OTOH,你的字符串列表确实非常长,请使用一个集合:

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

if facility in accepted_strings:
    do_stuff()

一组容器的测试平均为0(1)。

除非你的字符串列表变得非常长,否则像这样的东西可能是最好的:

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

if facility in accepted_strings:
    do_stuff()

要有效检查字符串是否与多个字符串中的一个匹配,请使用以下命令:

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

set()是散列的、无序的项集合,用于确定给定项是否在其中。

相关问题 更多 >