具有部分匹配的Python列表查找

Dav*_*hoe 12 python

对于以下列表:

test_list = ['one', 'two','threefour']
Run Code Online (Sandbox Code Playgroud)

如何判断项目是以"三个"开头还是以"四个"结尾?

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

two in test_list

我想像这样测试它:

startswith('three') in test_list.

我怎么做到这一点?

sth*_*sth 9

你可以使用any():

any(s.startswith('three') for s in test_list)
Run Code Online (Sandbox Code Playgroud)


sam*_*ias 7

您可以使用以下其中一种:

>>> [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
Run Code Online (Sandbox Code Playgroud)

  • + 1表示短路的.:) (2认同)