Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将字符串与多个项进行比较_Python_String_String Comparison - Fatal编程技术网

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

在Python中将字符串与多个项进行比较,python,string,string-comparison,Python,String,String Comparison,我试图将一个名为facility的字符串与多个可能的字符串进行比较,以测试它是否有效。有效字符串为: auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7 除了以下方法外,是否还有其他有效方法: if facility == "auth" or facility == "authpriv" ... 除非你的字符串列表长得可怕,否则像这样的东西可能是最

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

auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7
除了以下方法外,是否还有其他有效方法:

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

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

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()
s是散列的、无序的项集合,经过优化以确定给定项是否在其中。

如果字符串列表确实非常长,请使用集合:

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

if facility in accepted_strings:
    do_stuff()

一套容器的测试平均为O(1)。

哦,太棒了,谢谢。如果我的列表真的变长了怎么办?这只是一个小玩笑,因为你不想手工输入一个包含10000个字符串的列表。这是我最初使用的选项,但随着我的应用程序的发展,我将接受@pillmucher的答案。谢谢+1没问题。他的可能是更安全的一个,不过作为一个注意事项,在集合和列表包含之间的差异真正开始变得明显之前,你必须拥有比现在更大数量级的列表。记住,过早优化是万恶之源如果你担心速度,组装一个元组要比迭代创建集合的列表快一点。我不知道为什么。我的专长是CPython byte code manipulation.FWIW,在Python2.7和3中,您可以使用set literal语法:{'a','b','c'}是的,这就是方法。对于任何对python效率的一般概述感兴趣的人来说,这本书都是非常好的读物。虽然您不知道
set()
的平均时间,是吗?这样做的一个潜在缺点是迭代的顺序变得不可预测,但这只是在您将它们用于其他任何事情(例如在帮助消息中打印接受的字符串列表)时的一个问题。在python2.7/3中,您可以编写
accepted_strings={'auth','authpriv','daemon'}
,这样在构建集合之前就不会创建任何列表。要查找子字符串,请尝试一下,如果facility==“auth”或“authpriv”没有做他们想要做的事情(它会检查
facility==“auth”,许多新手都会被这一事实绊倒
为真
如果
“authpriv”
不是空字符串)。