2

特定の単語セットの文字列セットを検索し、さまざまなブール条件が満たされた場合にいくつかのアクションを実行しようとしています。現在、機能するアプローチがありますが、私が持っている方法よりもエレガントな方法があることを願っています。

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? これは不格好で非 Pythonic なアプローチのように見えるので、誰かがこれを行うための別の方法を持っていることを願っています。

4

2 に答える 2

4

これが最善の方法だとは思いませんが、できることの 1 つは、all他の 2 つのコントロール オブジェクトと組み合わせて使用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
于 2012-12-27T20:29:26.977 に答える
2
>>> 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
于 2012-12-27T20:29:15.987 に答える