python中字符串的冗长布尔搜索

2024-03-29 01:43:19 发布

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

我尝试在一组字符串中搜索一组特定的单词,并在满足各种布尔条件时执行一些操作。我目前有一个方法,但我希望有一个更优雅的方式比我现有的。在

strings = ['30 brown bears', '30 brown foxes', '20 green turtles', 
            '10 brown dogs']

for text in strings:
    if ('brown' in text) and ('bear' not in text) and ('dog' not in text):
        print text

这将按需要工作并打印30 brown foxes。然而,让我担心的是在搜索中添加更多的词汇。例如,如果“cat”、“mouse”、“rabbit”等都添加到if-statement中,会怎么样?这似乎是一种笨拙而非Python式的方式来处理事情,所以我希望有人能用不同的方法来完成。在


Tags: and方法字符串textinif方式not
2条回答

我怀疑这是最好的方法,但是您可以做的一件事是将all与其他两个控件对象结合使用—一个包含您要包含的项(在本例中是brown),另一个包含要忽略的项:

In [1]: strings = ['30 brown bears', '30 brown foxes', '20 green turtles', '10 brown dogs']

In [2]: keep = ('brown')

In [3]: ignore = ('bear', 'dog')

In [4]: for text in strings:
   ...:     if all([k in text for k in keep] + [i not in text for i in ignore]):
   ...:         print text
   ...:         
   ...:         
30 brown foxes
>>> strings = ['30 brown bears', '30 brown foxes', '20 green turtles', '10 brown dogs']
>>> conditions = [('brown', True), ('bear', False), ('dog', False)]
>>> for text in strings:
    if all((x in text) == c for x,c in conditions):
        print text

30 brown foxes

相关问题 更多 >