2011-05-24 76 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)