【问题标题】:Python index a list where a regex matchesPython索引一个正则表达式匹配的列表
【发布时间】:2013-05-12 05:28:30
【问题描述】:

再次认识到这与其他一些关于 SO 的问题相似,但我无法将其转换为我的目的。例如。用下面的sn-p

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

我希望能够得到一份清单

[2,4]

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

Python equivalent of which() in R

【问题讨论】:

  • 确定你想要[2,4]还是[1,3]? python 中的索引从 0 开始。因此,如果您希望使用这些值来索引原始列表,那么它们将是错误的。
  • 嗨@JonathonReinhart [1,3] 是对的。我的错误谢谢

标签: python regex list


【解决方案1】:
>>> 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]

注意 Python 使用 0-index,所以我将 start=1 参数添加到 enumerate。在实践中,您应该放弃 start=1 以使用默认的 start=0

【讨论】:

  • 哇,我不知道那个额外的参数。 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 2016-07-01
相关资源
最近更新 更多