# coding=utf-8 #http://www.secnetix.de/olli/Python/list_comprehensions.hawk #Construire des expressions mathématiques #en python est syntaxiquement très lisible #avec les comprehensions #S = {x² : x in {0 ... 9}} #V = (1, 2, 4, 8, ..., 2¹²) #M = {x | x in S and x even} if __name__ == '__main__': S = [x**2 for x in range(10)] V = [2**i for i in range(13)] M = [x for x in S if x % 2 == 0] print "Comprehension '[x**2 for x in range(10)]' :" print S print "Comprehension '[2**i for i in range(13)]' :" print V print "Comprehension '[x for x in S if x % 2 == 0]' :" print M #une comprehension peut prendre une liste de n'importe quel type #en arguments words = 'The quick brown fox jumps over the lazy dog'.split() print words stuff = [[w.upper(), w.lower(), len(w)] for w in words] for i in stuff: print i #une comprehension est une liste construite a partir #d'un generateur #firstn et firstn2 sont de même types : une liste # ( n for n in firstn_gen(10) ) est un generateur # c'est à dire un type d'iterateurs. firstn= [ n for n in xrange(10) ] firstngen= ( n for n in xrange(10) ) print "firstngen de type "+str(type(firstngen)) firstn2= list(firstngen) print " firstn de type "+str(type(firstn)) print " "+str(firstn) print " firstn2 de type "+str(type(firstn2)) print " "+str(firstn2)