[].index

Jeff Epler jepler at unpythonic.net
Mon May 31 10:48:40 EDT 2004


Using your test case:
>>> data = ['aaa','bbb','ccc','ddd','eee','fff','ggg','hhh'] 
>>> foo = ['b', 'e', 'e']

I'd define a function to do the difficult part:
(note that in Python 2.3, "s in t" returns True if s is a substring of t.
In earlier versions, "s in t" worked only when s was a length-1 string)
>>> def match(substring, candidates):
...     """Return the candidate which contains substring"""
...     for c in candidates:
...         if substring in c: return c

Then, the list comprehension becomes simple:
>>> [match(c, data) for c in foo]
['bbb', 'eee', 'eee']

Even if you want to write this as a single list comprehension, why not
>>> [iy for ix in foo for iy in data if ix in iy]
['bbb', 'eee', 'eee']
... though if some item in foo doesn't correspond to any items in data,
you just get a different-length output than input, not an exception (as
for your code) or a None in the resulting list (in my first example)

Personally, I'll take the approach that uses a function.  The
pure-listocmp version I wrote might as well say
>>> [fee fie foe fum i smell the blood of an englishman]
as far as my eyes are concerned.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040531/d7dd5e26/attachment.sig>


More information about the Python-list mailing list