Created
November 5, 2011 12:06
-
-
Save ksamuel/1341441 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| On peut aussi s'amuser avec les (peu connus) sets, qui sont built-in comme les dictionnaires:: | |
| In [1]: set((1,2,3,3,3,3,4)) # les set n'ont pas de doublons | |
| Out[1]: set([1, 2, 3, 4]) | |
| In [2]: 1 in set((1,2,3,4)) # operation O(1) comme les dicts | |
| Out[2]: True | |
| In [4]: set((1,2,3,4)).intersection((4,5,6)) # operations ensemblistes | |
| Out[4]: set([4]) | |
| Toutes les collections sont iterables, et donc on peut utiliser functions associées telle que zip() sur les listes, les tuples, les dicts, les sets, etc:: | |
| In [5]: d = {'moi':3, 'lui':4} | |
| In [6]: s = set(('bleu', 'rouge')) | |
| In [7]: zip(d, s) | |
| Out[7]: [('lui', 'bleu'), ('moi', 'rouge')] | |
| Et les itérables en Python ont un module rien que pour eux:: | |
| In [8]: import itertools | |
| In [9]: itertools.chain(d, s) | |
| Out[9]: <itertools.chain at 0x1f6c690> | |
| In [10]: list(itertools.chain(d, s)) | |
| Out[10]: ['lui', 'moi', 'bleu', 'rouge'] | |
| In [19]: tuple(itertools.combinations((1,2,3,4), 3)) | |
| Out[19]: ((1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)) | |
| Des itérables, on peut s'étendre sur les expressions génératrices:: | |
| In [21]: [x*2 for x in xrange(5)] | |
| Out[21]: [0, 2, 4, 6, 8] | |
| In [22]: (x*2 for x in xrange(5)) | |
| Out[22]: <generator object <genexpr> at 0x1f70280> | |
| In [23]: set((x*2 for x in xrange(5))) | |
| Out[23]: set([0, 8, 2, 4, 6]) | |
| Et après sur le mot clé yield, etc. Bref, le monde de la collection de données en Python et de son traitement est assez fun. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment