将字符串与 Python 中的多个项目进行比较 [英] Comparing a string to multiple items in Python

查看:49
本文介绍了将字符串与 Python 中的多个项目进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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" ...

推荐答案

如果 OTOH,您的字符串列表确实长得吓人,请使用集合:

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

测试集合中的包含性平均为 O(1).

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

这篇关于将字符串与 Python 中的多个项目进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆