From the time I started learning python, I began to summarize a collection of Python tips. And then when I was in stack Overflow
Or when I saw a cool piece of code in an open-source software, I was surprised that I could do it! , I tried to try this code myself, until I understood the whole idea, and I added the code to my collection. This blog is actually part of the public appearance of this collection after finishing. If you are already a Python Daniel, then basically you should know most of the usage, but I think you should also be able to find some new tricks you don't know. And if you were a C,c++,java programmer, learning python at the same time, or simply being a novice at just learning to program, you should see a lot of practical tricks that are especially useful to surprise you, just like I did.
Every skill and language usage is presented to you in one instance, and no other explanation is required. I've tried to make every example easy to understand, but because of the reader's familiarity with Python, there are still some obscure areas that may be unavoidable. So if these examples don't make you understand, at least the title of this example will help you when you go to Google search behind you.
The whole set is probably sorted by the difficulty level, simple and common in the front, relatively rare in the last.
1.1 Unpacking
>>> A, B, C = 1, 2, 3>>> A, B, C (1, 2, 3) >>> A, b, C = [1, 2, 3]>>> A, B, C (1, 2, 3) &G T;>> A, B, C = (2 * i + 1 for I in range (3)) >>> A, B, C (1, 3, 5) >>> A, (b, c), d = [1, (2, 3), 4]& Gt;>> a1>>> b2>>> c3>>> d4
1.2 Split-Box variable Exchange
>>> A, B = 1, 2>>> A, B = B, a>>> A, B (2, 1)
1.3 Expansion unboxing (compatible with Python3 only)
>>> A, *b, C = [1, 2, 3, 4, 5]>>> a1>>> b[2, 3, 4]>>> c5
1.4 Negative Index
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[-1]10>>> a[-3]8
1.5 Cut List
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[2:8][2, 3, 4, 5, 6, 7]
1.6 Negative Index cut list
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[-4:-2][7, 8]
1.7 Specifying the Step cut list
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[::2][0, 2, 4, 6, 8, 10]>>> a[::3][0, 3, 6, 9]&G T;>> a[2:8:2][2, 4, 6]
1.8 Negative Step cut list
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[::-1][10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]>>> a[:: -2][10, 8, 6, 4, 2, 0]
1.9 List Cut Assignment
>>> a = [1, 2, 3, 4, 5]>>> a[2:3] = [0, 0]>>> a[1, 2, 0, 0, 4, 5]>>> a[1:1] = [8, 9]&G T;>> a[1, 8, 9, 2, 0, 0, 4, 5]>>> a[1:-1] = []>>> a[1, 5]
1.10 Named List Cutting method
>>> a = [0, 1, 2, 3, 4, 5]>>> lastthree = Slice ( -3, none) >>> Lastthreeslice ( -3, none, none) > >> a[lastthree][3, 4, 5]
1.11 List and the compression and decompression of iterators
>>> a = [1, 2, 3]>>> b = [' A ', ' B ', ' C ']>>> z = Zip (A, b) >>> z[(1, ' a '), (2, ' B '), (3, ' C ')]>>> Zip (*z) [(1, 2, 3), (' A ', ' B ', ' C ')]
1.12 List of adjacent element compressors
>>> a = [1, 2, 3, 4, 5, 6]>>> Zip (* ([ITER (a)] * 2)) [(1, 2), (3, 4), (5, 6)] >>> group_adjacent = Lambda A, k:zip (* ([ITER (a)] * k)) >>> Group_adjacent (A, 3) [(1, 2, 3), (4, 5, 6)]>>> group_adjacent (A, 2) [(1, 2), (3, 4), (5, 6)]>>> group_adjacent (A, 1) [(1,), (2,), (3,), (4,), (5,), (6,)] >>> zip (a[::2), a [1::2]) [(1, 2), (3, 4), (5, 6)] >>> zip (A[::3], A[1::3], A[2::3]) [(1, 2, 3), (4, 5, 6)] >>> group_adjacent = LA MBDA A, K:zip (* (A[i::k] for I in range (k))) >>> Group_adjacent (A, 3) [(1, 2, 3), (4, 5, 6)]>>> Group_adja Cent (A, 2) [(1, 2), (3, 4), (5, 6)]>>> group_adjacent (A, 1) [(1,), (2,), (3,), (4,), (5,), (6,)]
1.13 Sliding the value window with a compressor and an iterator in the list
>>> def n_grams (A, N): ... z = [iter (a[i:]) for I in range (n)] ... return Zip (*z) ...>>> a = [1, 2, 3, 4, 5, 6]>>> N_grams (A, 3) [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)] >>> N_grams (A, 2) [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]>>> N_grams (A, 4) [(1, 2, 3, 4), (2, 3, 4, 5), ( 3, 4, 5, 6)]
1.14 Reversing a dictionary with a compressor
>>> m = {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}>>> M.items () [(' A ', 1), (' C ', 3), (' B ', 2), (' d ', 4)]>>> ; Zip (M.values (), M.keys ()) [(1, ' a '), (3, ' C '), (2, ' B '), (4, ' d ')]>>> mi = dict (Zip (m.values (), M.keys ())) >> > mi{1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}
1.15 List Expansion
>>> a = [[1, 2], [3, 4], [5, 6]]>>> list (Itertools.chain.from_iterable (a)) [1, 2, 3, 4, 5, 6] >>> ; Sum (A, []) [1, 2, 3, 4, 5, 6] >>> [x for L in a for x in L][1, 2, 3, 4, 5, 6] >>> a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]] >>> [x for L1 in a for L2 in L1-X in L2][1, 2, 3, 4, 5, 6, 7, 8] >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]>>> flatten = lambda x: [y for L in X for y in Flatten (l)] if type (x) is list else [x]>>> flatten (a ) [1, 2, 3, 4, 5, 6, 7, 8]
1.16 Generator Expression
>>> g = (x * * 2 for X in Xrange ()) >>> next (g) 0>>> next (g) 1>>> next (g) 4>>> n Ext (g) 9>>> sum (x * * 3 for X in Xrange ()) 2025>>> sum (x * * 3 for X in xrange () if x% 3 = = 1) 408
1.17 Dictionary Derivation
>>> m = {X:X * 2 for X in range (5)}>>> m{0:0, 1:1, 2:4, 3:9, 4:16} >>> m = {x: ' A ' + str (x) in}>>> m{0: ' A0 ', 1: ' A1 ', 2: ' A2 ', 3: ' A3 ', 4: ' A4 ', 5: ' A5 ', 6: ' A6 ', 7: ' A7 ', 8: ' A8 ', 9: ' A9 '}
1.18 Derivation of inverse dictionaries using dictionaries
>>> m = {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}>>> m{' d ': 4, ' A ': 1, ' B ': 2, ' C ': 3}>>> {v:k for k, V In M.items ()}{1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}
1.19 named tuples
>>> point = Collections.namedtuple ("point", [' X ', ' y ']) >>> p = Point (x=1.0, y=2.0) >>> ppoint ( x=1.0, y=2.0) >>> p.x1.0>>> p.y2.0
1.20 inheriting named tuples
>>> class Point (Collections.namedtuple (' pointbase ', [' X ', ' Y ')): ... __slots__ = () ... def __add__ (self, Other): ... Return point (x=self.x + other.x, Y=self.y + other.y) ...>>> p = Point (x=1.0, y=2.0) >>> q = Point (x=2.0, y =3.0) >>> p + qpoint (x=3.0, y=5.0)
1.21 operation set
>>> A = {1, 2, 3, 3}>>> Aset ([1, 2, 3]) >>> B = {3, 4, 5, 6, 7}>>> Bset ([3, 4, 5, 6, 7] ) >>> A | Bset ([1, 2, 3, 4, 5, 6, 7]) >>> A & Bset ([3]) >>> a-bset ([1, 2]) >>> B-aset ([4, 5, 6, 7]) & Gt;>> a ^ Bset ([1, 2, 4, 5, 6, 7]) >>> (a ^ B) = = ((A) | (B-A)) True
1.22 manipulating multiple collections
>>> A = collections. Counter ([1, 2, 2]) >>> B = collections. Counter ([2, 2, 3]) >>> Acounter ({2:2, 1:1}) >>> Bcounter ({2:2, 3:1}) >>> A | Bcounter ({2:2, 1:1, 3:1}) >>> A & Bcounter ({2:2}) >>> A + bcounter ({2:4, 1:1, 3:1}) >>> A-bcounter ({1:1}) >>> B-acounter ({3:1})
1.23 statistics The most commonly occurring elements in an iterator
>>> A = collections. Counter ([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]) >>> Acounter ({3:4, 1:2, 2:2, 4:1, 5:1, 6:1, 7:1}) >>> A.most_common (1) [(3, 4)]>>> A.most_common (3) [(3, 4), (1, 2), (2, 2)]
1.24 operational queues at both ends
>>> Q = Collections.deque () >>> q.append (1) >>> Q.appendleft (2) >>> q.extend ([3, 4]) >>> Q.extendleft ([5, 6]) >>> Qdeque ([6, 5, 2, 1, 3, 4]) >>> Q.pop () 4>>> q.popleft () 6& Gt;>> Qdeque ([5, 2, 1, 3]) >>> q.rotate (3) >>> qdeque ([2, 1, 3, 5]) >>> q.rotate ( -3) >& Gt;> Qdeque ([5, 2, 1, 3])
1.25 double-ended queue with maximum length
>>> Last_three = Collections.deque (maxlen=3) >>> for me in Xrange (Ten): ... Last_three.append (i) ... print ', '. Join (str (x) for x in Last_three) ... 00, 10, 1, 21, 2, 32, 3, 43, 4, 54, 5, 65, 6, 76, 7, 87, 8, 9
1.26 sortable Dictionaries
>>> m = dict ((str (x), X) for x in range) >>> print ', '. Join (M.keys ()) 1, 0, 3, 2, 5, 4, 7, 6, 9, 8> ;>> m = collections. Ordereddict ((str (x), X) for x in range) >>> print ', '. Join (M.keys ()) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9>>> m = collections. Ordereddict ((str (x), X) for x in range (0,-1)) >>> print ', '. Join (M.keys ()) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
1.27 Default Dictionaries
>>> m = dict () >>> m[' a ']traceback (most recent call last): File "<stdin>", line 1, in <modu Le>keyerror: ' A ' >>>>>> m = collections.defaultdict (int) >>> m[' a ']0>>> m[' B ']0 >>> m = collections.defaultdict (str) >>> m[' a '] ' >>> m[' B '] + = ' A ' >>> m[' B '] ' a ' > >> m = collections.defaultdict (lambda: ' [Default value] ') >>> m[' a '] ' [default value] ' >>> m[' B '] ' [Default value] '
1.28 Simple tree representation of the default dictionary
>>> import json>>> tree = lambda:collections.defaultdict (tree) >>> root = Tree () >>> root[' Menu ' [' id '] = ' file ' >>> root[' menu ' [' value '] = ' file ' >>> root[' menu ' [' MenuItems '] [' new '] [ ' Value ' = ' new ' >>> root[' menu ' [' MenuItems '] [' new '] [' onclick '] = ' new (); ' >>> root[' menu ' [' MenuItems '] [' open '] [' value '] = ' open ' >>> root[' menu ' [' MenuItems '] [' open '] [' OnClick '] = ' open (); ' >>> root[' menu ' [' MenuItems '] [' close '] [' value '] = ' close ' >>> root[' menu ' [' MenuItems '] [' close '] [ ' onclick '] = ' close (); ' >>> print json.dumps (root, Sort_keys=true, indent=4, separators= (', ', ': ')) {"Menu": {"id": "File", "MenuItems": {"close": {"onclick": "Close ();", "Value": "Close" }, "new": {"onclick": "New ();", "Value": "New"}, "open" : {"onclick": "Open ();", "Value": "Open"}, "value": "File"}
1.29 Object-to-unique-count mappings
>>> import Itertools, collections>>> value_to_numeric_map = Collections.defaultdict ( Itertools.count (). Next) >>> value_to_numeric_map[' a ']0>>> value_to_numeric_map[' B ']1>> > value_to_numeric_map[' C ']2>>> value_to_numeric_map[' a ']0>>> value_to_numeric_map[' B ']1
1.30 Maximum and minimum number of list elements
>>> a = [Random.randint (0, +) for __ in xrange (+)]>>> heapq.nsmallest (5, a) [3, 3, 5, 6, 8]>>&G T Heapq.nlargest (5, a) [100, 100, 99, 98, 98]
1.31 Cartesian product of two lists
>>> for P in Itertools.product ([1, 2, 3], [4, 5]):(1, 4) (1, 5) (2, 4) (2, 5) (3, 4), 3, 5, >>> for P in Itert Ools.product ([0, 1], repeat=4): ... print '. Join (str (x) for x in P) ... 0000000100100011010001010110011110001001101010111100110111101111
1.32 list combinations and list element substitution combinations
>>> for C in Itertools.combinations ([1, 2, 3, 4, 5], 3): ... print '. Join (str (x) for x in C) ... 123124125134135145234235245345>>> for C in Itertools.combinations_with_replacement ([1, 2, 3], 2): ... print '. Join (str (x) for x in C) ... 111213222333
1.33 list element permutation combinations
>>> for P in Itertools.permutations ([1, 2, 3, 4]): ... print '. Join (str (x) for x in P) ... 123412431324134214231432213421432314234124132431312431423214324134123421412341324213423143124321
1.34 Link iterators
>>> a = [1, 2, 3, 4]>>> for P in Itertools.chain (Itertools.combinations (A, 2), Itertools.combinations (A, 3)): ... Print P ... (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4) (1, 2, 3) (1, 2, 4) (1, 3, 4) (2, 3, 4) >>> for subset in Itertools.chain.from_iterable (Itertools.combinations (A, n) for n in range (Len (a) + 1)) ... Print subset ... () (1,) (2,) (3,) (4,) (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4) (1, 2, 3) (1, 2, 4) (1, 3, 4) (2, 3, 4) (1, 2, 3, 4)
1.35 specifying columns by file clustering
>>> Import itertools>>> with open (' Contactlenses.csv ', ' R ') as infile: ... data = [Line.strip (). Split (', ') for line in infile]...>>> data = data[1:]>>> def print_data (rows): ... print ' \ n '. Join (' \ t '. Joi N (' {: <16} '. Format (s) for S-in row) ... >>> print_data (data) Young Myope No reduced Noneyoung Myope No Normal Softyoung Myope Yes reduced Noneyoung Myope Yes normal Hardyoung Hypermetrope no reduced Noneyoung hypermetrope No normal Softyoung Hypermetrope Yes ReducedNoneyoung Hypermetrope Yes normal hardpre-presbyopic my Ope no reduced nonepre-presbyopic myope No Normal Softpre-presbyopic Myope Yes reduce D nonepre-presbyopic myope Yes normal hardpre- Presbyopic hypermetrope no reduced nonepre-presbyopic Hypermetro PE no normal softpre-presbyopic hypermetrope Yes Reduced Nonepre-presbyopic Hypermetrope Yes normal Nonepresbyopic Myope No reduced nonepresbyopic Myope No normal nonepresbyopic Myope Yes Reduced Nonepresbyopic Myope Yes normal Hardpresbyopic Hypermetrope No reduced nonepresbyopic Hypermetrope no normal softpresbyopic Hypermetrope Yes reduced nonepresbyopic Hypermetrope Yes No Rmal None >>> Data.sort (Key=lambda r:r[-1]) >>> for value, group in Itertools.groupby (d ATA, Lambda r:r[-1]): ... print '-----------' ... print ' Group: ' + value ... print_data (Group) ...-----------Gro Up:hardyoung Myope Yes normal Hardyoung Hypermetrope Yes normal Hardpre-presbyopic Myope Yes Normal hardpresbyopic myope yes normal ha Rd-----------Group:noneyoung Myope no reduced noneyo Ung myope Yes reduced Noneyoung Hypermet Rope no reduced Noneyoung hypermetrope Yes Reduced Nonepre-presbyopic Myope No reduced Nonepre-presbyopic Myope Yes reduced Nonepre-presby OPIc hypermetrope no reduced nonepre-presbyopic hypermetrope Yes Reduced Nonepre-presbyopic Hypermetrope Yes normal Nonepresbyopic Myope No reduced nonepresbyopic Myope no normal nonepresbyopic Myope Yes reduced nonepresbyopic Hypermetrope No Reduced Nonepresbyopic Hypermetrope Yes reduced no Nepresbyopic Hypermetrope Yes normal none-----------Group:softyo Ung myope no normal Softyoung Hypermet Rope no normal softpre-presbyopic myope no Normal Softpre-presbyopic Hypermetrope No normal SOFTPRESBYOP IC Hypermetrope no normal soft
30 Tips for Python