2

Again recognizing that this is similar to a few other questions on SO but which I haven't been able to convert for my purposes. eg. with the snippet below

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

I'd like to be able to get a list

[2,4]

which is the index of the two custard strings. I thought the question below would help but I haven't been able to figure out how to apply it here.

Python equivalent of which() in R

Community
  • 1
  • 1
Tahnoon Pasha
  • 5,848
  • 14
  • 49
  • 75
  • 4
    Are you *sure* you want `[2,4]` or do you want `[1,3]`? Indexes in python start at 0. So if you're looking to use those values to index into the original list, they will be wrong. – Jonathon Reinhart May 17 '13 at 06:00

1 Answers1

11
>>> 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]

note Python uses 0-index so I added the start=1 parameter to enumerate. In practice you should leave off start=1 to have the default start=0.

jamylak
  • 128,818
  • 30
  • 231
  • 230