[Array] Finding index that contains part of a string?

G

Gilles Ganault

Hello

Out of curiosity, is there a better way in Python to iterate through
an array, and return the index of each item that contains the bit
somewhere in its value, ie. index() doesn't work because it only
returns if the value only contains the item I'm looking for.

This works:
========
next = re.compile(">&#9658<")
i = 0
for item in items:
m = next.search(item)
if m:
print "Found Next in item %s" % i
i = i + 1
========

Thank you.
 
T

Tim Chase

Out of curiosity, is there a better way in Python to iterate through
an array, and return the index of each item that contains the bit
somewhere in its value, ie. index() doesn't work because it only
returns if the value only contains the item I'm looking for.

This works:
========
next = re.compile(">&#9658<")
i = 0
for item in items:
m = next.search(item)
if m:
print "Found Next in item %s" % i
i = i + 1

It looks like you're hunting for a fixed string, so I'd use

">&#9658<" in item

instead of bothering with a regexp.

You could do something like

indicies = [i for (i, item)
in enumerate(items)
if ">&#9658<" in item
# if next.search(item)
]

Or, if you just want those those indicies to find the
corresponding items, you can skip the enumerate()

indicies = [item for item in items
if ">&#9658<" in item
# if next.search(item)
]

You can use the "enumerate()" wrapper to get the indicies in your
loop if you really have to process them as such

for i, item in enumerate(items):
# if next.search(item)
if ">&#9658<" in item:
print "Found next item at", i

which is a bit more pythonic than "i = 0 ... i += 1"

-tkc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top