How to create two loops for presentation in python

I have two lists as below

tags = [u'man', u'you', u'are', u'awesome'] entries = [[u'man', u'thats'],[ u'right',u'awesome']] 

I want to extract entries from entries when they are in tags :

 result = [] for tag in tags: for entry in entries: if tag in entry: result.extend(entry) 

How can I write two loops as an understanding of one line?

+42
python list for-loop list-comprehension
Aug 31 '13 at 18:25
source share
3 answers

This should do it:

 [entry for tag in tags for entry in entries if tag in entry] 
+53
Aug 31 '13 at 18:28
source share

The best way to remember this is that the order of the for loop inside the list comprehension is based on the order in which they appear in the traditional loop. First the outermost loop begins, and then the inner loops.

So, understanding an equivalent list would be as follows:

 [entry for tag in tags for entry in entries if tag in entry] 

Usually the if-else comes before the first for loop, and if you only have an if , it will complete. For example, if you want to add an empty list if the tag not in the record, you should do it like this:

 [entry if tag in entry else [] for tag in tags for entry in entries] 
+71
Aug 31 '13 at 18:28
source share

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 ))

+3
Aug 31 '13 at 18:27
source share



All Articles