You may not know the characteristics of the 30 Python language skills

Source: Internet
Author: User

1 Introduction

From the time I started learning Python, I decided to maintain a frequently used "tips" list. Whenever I see a paragraph that makes me feel "cool, it's OK!" "Code (in an example, in StackOverflow, in the open source software, and so on), I'll try it until I understand it and add it to the list. This article is part of the cleanup list. If you are an experienced Python programmer, though you may already know something, you can still find something you do not know. If you are a C, C + + or Java programmer who is learning python, or have just started to learn programming, you will find many of them very useful as I do.

Each trick or language feature can only be verified by an instance, without too much explanation. Although I have tried to make the examples clear, some of them will still look complicated, depending on how familiar you are. So if you're not sure if you've seen an example, the headline will provide you with enough information to get detailed content from Google.

Lists are sorted by difficulty, with common language features and techniques in front of them.

  1.1 Spin-offs

>>> 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 Swap variable Split

>>> A, B = 1, 2>>> A, B = B, a>>> A, B (2, 1)

1.3 Extended spin-off (Python 3 applies)

>>> 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 list slices (A[start:end])

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[2:8][2, 3, 4, 5, 6, 7]

1.6 list slices with negative indexes

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> a[-4:-2][7, 8]

1.7 list slice with step value (A[start:end:step])

>>> 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 worthwhile list slice

>>> 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 Slice 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 slices (slice (start, end, step))

>>> a = [0, 1, 2, 3, 4, 5]>>> lastthree = Slice ( -3, none) >>> Lastthreeslice ( -3, none, none) > >> a[lastthree][3, 4, 5]

1.11 Zip package unpacking list and multiples

>>> 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 Merging adjacent list items with a zip

>>> 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 = Lambda A, K:zip (* (A[i::k] for I in range (k))) >>> Group_adjacent (A, 3) [(1, 2, 3), (4, 5, 6)]>>> group_a Djacent (A, 2) [(1, 2), (3, 4), (5, 6)]>>> group_adjacent (A, 1) [(1,), (2,), (3,), (4,), (5,), (6,)]

1.13 Creating sliding windows using Zip and iterators (n-grams)

>>> from itertools import islice>>> def n_grams (A, N): ...     z = (Islice (A, I, None) 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 Using the zip inversion dictionary

>>> 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 Leveling list:

>>> 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-X in L][1, 2, 3, 4, 5, 6]>>> a = [[1, 2], [3, 4]], [ [5, 6], [7, 8]]]>>> [x for L1 in a-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] Note: According to the Python documentation, Itertools.chain.from_iterable is preferred.

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 Iteration Dictionaries

>>> 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 reversing a dictionary by iterating through a dictionary

>>> 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 sequence (collections.namedtuple)

>>> 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 Inheritance of named lists:

>>> 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 Collection and collection operations

>>> 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 multi-set and its operation (collections. Counter)

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

The most common element in the 1.23 iteration (collections. Counter)

>>> 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 Dual-ended queue (Collections.deque)

>>> 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 (collections.deque)

>>> 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 dictionary sort (collections. ORDEREDDICT)

>>> 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 dictionary (collections.defaultdict)

>>> 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 using the default dictionary to represent a simple tree

>>> 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"} (to https://gist.github.com/hrldcpr/2012250 View details Cia

1.29 mapping an object to a unique sequence number (collections.defaultdict)

>>> 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 minimum elements (Heapq.nlargest and Heapq.nsmallest)

>>> 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 (itertools.product)

>>> 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 combination of combinations and permutations (itertools.combinations and Itertools.combinations_with_replacement)

>>> 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 Sort (itertools.permutations)

>>> for P in Itertools.permutations ([1, 2, 3, 4]):     ... print '. Join (str (x) for x in P) ... 123412431324134214231432213421432314234124132431312431423214324134123421412341324213423143124321

1.34 linked iterations (itertools.chain)

>>> 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 grouping rows by given value (ITERTOOLS.GROUPBY)

>>> from operator import itemgetter>>> import itertools>>> with open (' Contactlenses.csv ', ' r As infile: ... data = [Line.strip (). Split (', ') for line in infile]...>>> data = data[1:]>>> def PR Int_data (rows): ... print ' \ n '. Join (' \ t '. Join (' {: <16} '. Format (s) for S-in row) for row in rows) ...>>> Prin               T_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 hy  Permetrope Yes                   Reduced Noneyoung Hypermetrope Yes normal Hardpre-presbyopic Myope No reduced nonepre-p                   Resbyopic myope no normal softpre-presbyopic Myope                     Yes reduced nonepre-presbyopic Myope Yes                 Normal Hardpre-presbyopic Hypermetrope no reduced Nonepre-presbyopic Hypermetrope No normal Softpre-presbyopi            C Hypermetrope Yes reduced nonepre-presbyopic hypermetrope                      Yes normal nonepresbyopic Myope no              Reduced   Nonepresbyopic Myope No normal nonepresbyopic Myope Yes reduced nonepresbyopic myope y Es normal hardpresbyopic Hypermetrope no red uced nonepresbyopic hypermetrope No normal softp Resbyopic hypermetrope Yes reduced nonepresbyopic hyperme Trope Yes normal none>>> data.sort (Key=itemgetter ( -1)) >>&gt ; For value, group in Itertools.groupby (data, Lambda r:r[-1]): ... print '-----------' ... print ' group: ' + value '.     .                  Print_data (Group) ...-----------Group:hardyoung myope Yes normal HardyOung hypermetrope Yes normal hardpre-presbyopic myope                     Yes normal Hardpresbyopic Myope Yes                      Normal hard-----------Group:noneyoung Myope No                 Reduced Noneyoung Myope Yes reduced               Noneyoung Hypermetrope No reduced Noneyoung                   Hypermetrope Yes reduced nonepre-presbyopic myope                     No reduced nonepre-presbyopic Myope Yes                 Reduced Nonepre-presbyopic Hypermetrope No reduced     Nonepre-presbyopic Hypermetrope Yes reduced nonepre-presbyopic hypermetrope y Es normal nonepresbyopic Myope no red uced nonepresbyopic myope No normal NONEP Resbyopic myope Yes reduced nonepresbyopic hyperme                     Trope no reduced nonepresbyopic hypermetrope Yes                  Reduced Nonepresbyopic Hypermetrope Yes normal                  None-----------Group:softyoung myope no normal Softyoung Hypermetrope No normal Softpre-presbyopi            C Myope       No normal softpre-presbyopic Hypermetrope no                  Normal Softpresbyopic Hypermetrope no normal Soft

Original address: http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html

You may not know the characteristics of the 30 Python language skills

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.