2012-12-27 25 views
2

我試圖搜索一組特定字詞的字符串,並在滿足各種布爾條件時執行一些操作。我現在有一個可行的方法,但我希望有比我更優雅的方式。冗長的布爾搜索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。然而,我擔心的是在搜索中增加更多條款。例如,如果「貓」,「鼠標」,「兔子」等全部添加到if-statement?這似乎是一種笨拙的,非Pythonic的方式來處理事情,所以我希望有人有不同的方式來完成這件事。

回答

4

我懷疑這是最好的辦法,但有一兩件事你可以做的是結合使用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 
+0

我們有類似的想法,但我更喜歡你的想法。 –

+0

我非常喜歡這兩個想法,但我會繼續並接受這個想法,但我非常喜歡這兩個答案,並且可能會在兩個方面都發揮。謝謝你們的幫助! – user1074057

+0

@ user1074057完全沒問題,開心幫忙! – RocketDonkey

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 
+0

+1 - 我喜歡將條件與單詞配對。 – RocketDonkey