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

1
  • 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. Commented May 17, 2013 at 6:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I did not know about that extra parameter. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.