[].index
Calvin Spealman
calvin at ironfroggy.com
Mon May 31 06:29:47 EDT 2004
Mike Edey wrote:
> Good day.
> Recently I'd run into wishing a list's index method would match
> substrings. Being fairly new to this game I can't help but think that my
> solution is a little, well, clumsy. In the following trivial example I'm
> only interested in finding the first matching list item:
>
>>>> data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] foo =
>>>> ['b','e','e']
>>>> [data[[data.index(iy) for iy in data if iy.find(foo[ix]) > -1][0]] for
>>>> ix in range(len(foo))]
>
> ['bbb', 'eee', 'eee']
>
>
> So I guess this question is - have I missed a cleaner method then this
> nested list comprehension?
This depends on what you need this for exactly. Will you always be matching
a single character to the beginning of a string or will they sometimes be
more than one character? if only one, then how about storing the strings as
a dict with the characters as keys?
More information about the Python-list
mailing list