python,“a in b”关键字,多个a怎么样?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/763944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:49:16  来源:igfitidea点击:

python, "a in b" keyword, how about multiple a's?

python

提问by grigoryvp

My adventures in Python continue and my favorite books are silent again. Python offers a built-in way to test if a variable is inside an iterable object, using the 'in' keyword:

我在 Python 中的冒险仍在继续,而我最喜欢的书又沉默了。Python 提供了一种内置方法来测试变量是否在可迭代对象内,使用 'in' 关键字:

if "a" in "abrakadabra" :
  print "it is definitely here"

But is it possible to test if more than one item is in the list (any one)? Currently, I'm using the syntax below, but it is kinda long:

但是是否可以测试列表中是否有多个项目(任何一个)?目前,我正在使用下面的语法,但它有点长:

if "// @in " in sTxt or "// @out " in sTxt or "// @ret " in sTxt or <10 more>
  print "found."

Of course regexes can help, but using regexes will take lots of verbose of code and will not be as clear as "a in b". Are there any other Pythonic ways?

当然,正则表达式会有所帮助,但使用正则表达式会占用大量冗长的代码,而且不会像“a in b”那样清晰。有没有其他 Pythonic 方式?

回答by Markus Jarderot

alternatives = ("// @in ", "// @out ", "// @ret ")
if any(a in sTxT for a in alternatives):
    print "found"

if all(a in sTxT for a in alternatives):
   print "found all"

any()and all()takes an iterable and checks if any/all of them evaluate to a true value. Combine that with a generator expressions, and you can check multiple items.

any()all()接受一个迭代并检查它们中的任何一个/全部是否评估为真值。将其与生成器表达式结合使用,您可以检查多个项目。

回答by Benjamin Peterson

any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))

any(snippet in text_body for snippet in ("hi", "foo", "bar", "spam"))

回答by Brian

If you're testing lots of lines for the same words, it may be faster to compile them as a regular expression. eg:

如果您要为相同的单词测试很多行,将它们编译为正则表达式可能会更快。例如:

import  re
words = ["// @in ", "// @out ", "// @ret "] + ["// @test%s " % i for i in range(10)]

my_regex = re.compile("|".join(map(re.escape, words)))

for line in lines_to_search:
    if my_regex.search(line):  print "Found match"

Some quick timing shows that this is usually faster than the any(word in theString for word in words)approach. I've tested both approaches with varying text (short/long with/without matches). Here are the results:

一些快速计时表明这通常比any(word in theString for word in words)方法更快。我已经用不同的文本(有/无匹配的短/长)测试了这两种方法。结果如下:

         { No keywords  } |  {contain Keywords }
         short    long       short    long
regex  : 0.214    27.214     0.147    0.149
any in : 0.579    81.341     0.295    0.300

If performance doesn't matter though, the any()approach is more readable.

如果性能无关紧要,则该any()方法更具可读性。

回答by mazunki

This must be an old post, now the simplest way to do it is with a list:

这一定是一个旧帖子,现在最简单的方法是使用列表:

a = "some long text which may or may not include bononos or cabbages"
alternatives = ["apple", "banana", "riverdale"]
if a in alternatives:
    print("Hm?")

回答by Esteban Küber

If you want anycheck then you would use this:

如果你想要任何检查,那么你可以使用这个:

inthere = False
checks = ('a', 'b')

for check in checks:
    if check in 'abrakadabra':
        inthere = True
        break

If you want allcheck out you could use this:

如果你想全部退房,你可以使用这个:

inthere = True
checks = ('a', 'b')

for check in checks:
    if check not in 'abrakadabra':
        inthere = False
        break

EDIT: Didn't know the more pythonic any(). It's probably better to use that on python.

编辑:不知道更多的 pythonic any()。在 python 上使用它可能更好。

EDIT2: Added break statements, and corrected the all-case.

EDIT2:添加了 break 语句,并更正了所有情况。

回答by allyourcode

You could also use set methods and operators:

您还可以使用set 方法和运算符

not alternatives.isdisjoint(sTxt)  # for "any"
(alternatives & sTxt) != set()  # Again, the intersection is nonempty
alternatives <= sTxt  # for "all"

I think these are easier to read than using the any or all, but have to convert your collections into sets. Since intersection and containment are what you care about, you might consider making them sets in the first place.

我认为这些比使用 any 或 all 更容易阅读,但必须将您的集合转换为集合。由于交叉和遏制是您关心的,您可能首先考虑将它们设置。

回答by Rory

There's no built in way in the syntax to do it. However you can use the 'any' function to make it easier as @MizardX and @Benjamin Peterson showed.

语法中没有内置的方法来做到这一点。但是,正如@MizardX 和@Benjamin Peterson 所展示的那样,您可以使用“任何”函数使其更容易。