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

Discussion in 'Python' started by Gilles Ganault, Nov 12, 2008.

  1. 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.
     
    Gilles Ganault, Nov 12, 2008
    #1
    1. Advertisements

  2. Gilles Ganault

    Tim Chase Guest

    Out of curiosity, is there a better way in Python to iterate through
    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
     
    Tim Chase, Nov 12, 2008
    #2
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.