部分匹配的Python列表查找

部分匹配的Python列表查找,python,Python,有关以下列表: test_list = ['one', 'two','threefour'] 我如何确定一个项目是以“三”开头还是以“四”结尾 例如,不要像这样测试成员资格: 测试列表中的两个 我想这样测试它: 在测试列表中以('三')开始测试 我将如何实现这一点?您可以使用以下方法之一: >>> [e for e in test_list if e.startswith('three') or e.endswith('four')] ['threefour'] >&g

有关以下列表:

test_list = ['one', 'two','threefour']
我如何确定一个项目是以“三”开头还是以“四”结尾

例如,不要像这样测试成员资格:

测试列表中的两个

我想这样测试它:

在测试列表中以('三')开始测试


我将如何实现这一点?

您可以使用以下方法之一:

>>> [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
应该有帮助

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)搜索-如果它找到匹配的元素作为第一个条目或沿着这些行的任何内容,它不会短路。

您可以使用:

any(s.startswith('three') for s in test_list)