- Item 1
- Item 2
- Item 3
- 项目1
- 项目2
- 项目3
test_list = ['one', 'two','threefour']
如何判断一个列表中的元素是否以'three'开头或以'four'结尾?
举个例子,不是像这样测试成员资格:
two in test_list
我想要这样测试:
startswith('three') in test_list
。
我该如何实现?
test_list = ['one', 'two','threefour']
如何判断一个列表中的元素是否以'three'开头或以'four'结尾?
举个例子,不是像这样测试成员资格:
two in test_list
我想要这样测试:
startswith('three') in test_list
。
我该如何实现?
any()
函数:any(s.startswith('three') for s in test_list)
>>> [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
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)
if [s for s in test_list if s.startswith('three')]:
# something here for when an element exists that starts with 'three'.
请注意,这是一个O(n)搜索 - 如果它在第一个条目或任何其他地方找到匹配的元素,它不会短路。