【发布时间】:2023-03-29 13:23:01
【问题描述】:
对于以下列表:
test_list = ['one', 'two','threefour']
我如何知道一个项目是以“三”开头还是以“四”结尾?
例如,不要像这样测试成员资格:
two in test_list
我想这样测试它:
startswith('three') in test_list.
我将如何做到这一点?
【问题讨论】:
标签: python
对于以下列表:
test_list = ['one', 'two','threefour']
我如何知道一个项目是以“三”开头还是以“四”结尾?
例如,不要像这样测试成员资格:
two in test_list
我想这样测试它:
startswith('three') in test_list.
我将如何做到这一点?
【问题讨论】:
标签: python
你可以使用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) 搜索 - 如果它找到一个匹配元素作为第一个条目或任何类似的内容,它不会短路。
【讨论】: