Python索引正则表达式匹配的列表

Tah*_*sha 2 python regex list

再次认识到这与SO上的一些其他问题类似但我无法为我的目的转换.例如.用下面的代码片段

import re
a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake']
s = re.compile('custard')
Run Code Online (Sandbox Code Playgroud)

我希望能够得到一份清单

[2,4]

这是两个custard字符串的索引.我认为下面的问题会有所帮助,但我无法弄清楚如何在这里应用它.

Python相当于R中的which()

jam*_*lak 9

>>> import re
>>> a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake']
>>> [i for i, s in enumerate(a, start=1) if re.search('custard', s)]
[2, 4]
Run Code Online (Sandbox Code Playgroud)

注意 Python使用0索引,所以我添加了start=1参数enumerate.在实践中,你应该离开start=1以获得默认值start=0.

  • 哇,我不知道那个额外的参数。+1 (2认同)