[Array] Finding index that contains part of a string?
Tim Chase
python.list at tim.thechases.com
Wed Nov 12 09:06:18 EST 2008
> 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(">►<")
> 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
">►<" in item
instead of bothering with a regexp.
You could do something like
indicies = [i for (i, item)
in enumerate(items)
if ">►<" 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 ">►<" 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 ">►<" in item:
print "Found next item at", i
which is a bit more pythonic than "i = 0 ... i += 1"
-tkc
More information about the Python-list
mailing list