Python列表使用部分匹配进行查找

16
  • 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

我该如何实现?

4个回答

13
你可以使用 any() 函数:
any(s.startswith('three') for s in test_list)

这个查找的时间复杂度是多少?它是否仍然与集合查找渐进等价? - Dr. Strangelove

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

3

1
如果你正在寻找一种在条件语句中使用它的方法,你可以这样做:
if [s for s in test_list if s.startswith('three')]:
  # something here for when an element exists that starts with 'three'.

请注意,这是一个O(n)搜索 - 如果它在第一个条目或任何其他地方找到匹配的元素,它不会短路。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接