2011-05-24 73 views
9

對於下面的列表:Python列表查找與部分匹配

test_list = ['one', 'two','threefour'] 

我怎麼會發現,如果一個項目有「三」開頭或以「四」結束?

例如,而不是測試的會員是這樣的:

two in test_list

我想測試這樣的:

startswith('three') in test_list

我該如何做到這一點?

回答

4

你可以使用其中之一:

>>> [e for e in test_list if e.startswith('three') or e.endswith('four')] 
['threefour'] 
>>> any(e for e in test_list if e.startswith('three') or e.endswith('four')) 
True 
+2

+1了其中一個會短路。 :) – 2011-05-24 21:56:20

0

如果你正在尋找一種方式來使用,在有條件的你可以這樣:

if [s for s in test_list if s.startswith('three')]: 
    # something here for when an element exists that starts with 'three'. 

要知道,這是一個O(n)的搜索 - 它不會短如果它找到匹配的元素作爲第一個條目或沿着這些條目的任何東西,則爲電路。

6

您可以使用any()

any(s.startswith('three') for s in test_list)