Python 列表的部分匹配查找
对于下面这个列表:
test_list = ['one', 'two','threefour']
我该如何判断一个项目是否以'three'开头或者以'four'结尾呢?
举个例子,我不想像这样测试是否存在:
two in test_list
我想像这样测试:
startswith('three') in test_list
。
我该怎么做呢?
4 个回答
3
这个链接可能会对你有帮助:http://www.faqs.org/docs/diveintopython/regression_filter.html
test_list = ['one', 'two','threefour']
def filtah(x):
return x.startswith('three') or x.endswith('four')
newlist = filter(filtah, test_list)
9
你可以使用以下其中之一:
>>> [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
13
你可以使用 any()
这个函数:
any(s.startswith('three') for s in test_list)