[].index
Shalabh Chaturvedi
shalabh at cafepy.com
Mon May 31 12:52:13 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?
Here's an option:
[s for s in data for prefix in foo if s.startswith(prefix)]
Clearer to read and understand. I like to keep away from indexes and
counters as much as possible.
HTH,
Shalabh
More information about the Python-list
mailing list