The corresponding LC will be
[entry for tag in tags for entry in entries if tag in entry]
The order of loops in LC is similar to the order in nested loops, if statements go to the end, and conditional expressions go to the beginning, something like
[a if a else b for a in sequence]
See demo -
>>> tags = [u'man', u'you', u'are', u'awesome'] >>> entries = [[u'man', u'thats'],[ u'right',u'awesome']] >>> [entry for tag in tags for entry in entries if tag in entry] [[u'man', u'thats'], [u'right', u'awesome']] >>> result = [] for tag in tags: for entry in entries: if tag in entry: result.append(entry) >>> result [[u'man', u'thats'], [u'right', u'awesome']]
EDIT . Since you need the result to be flattened, you could use a similar list comprehension and then smooth out the results.
>>> result = [entry for tag in tags for entry in entries if tag in entry] >>> from itertools import chain >>> list(chain.from_iterable(result)) [u'man', u'thats', u'right', u'awesome']
Add this together, you can just do
>>> list(chain.from_iterable(entry for tag in tags for entry in entries if tag in entry)) [u'man', u'thats', u'right', u'awesome']
Here you use a generator expression instead of a list comprehension. (The limit of 79 characters fits perfectly (without calling list ))
Sukrit Kalra Aug 31 '13 at 18:27 2013-08-31 18:27
source share