Piet van Oostrum piet at cs.uu.nl
Wed Jun 2 13:43:40 CEST 2004

>>>>> Mike Edey <mike at edey.mine.nu> (ME) wrote:

ME> Good day.
ME> Recently I'd run into wishing a list's index method would match
ME> substrings. Being fairly new to this game I can't help but think that my
ME> solution is a little, well, clumsy. In the following trivial example I'm
ME> 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))]

ME> ['bbb', 'eee', 'eee']

ME> So I guess this question is - have I missed a cleaner method then this
ME> nested list comprehension?

It can be cleaned up:

[d for d in data for x in foo if d.find(x) > -1]
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl

More information about the Python-list mailing list