Must-see 30 Python language Features tips (2)

Source: Internet
Author: User
From the time I started learning http://www.php.cn/wiki/1514.html "target=" _blank ">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.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 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 for 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 (10))

>>> Next (g)

0

>>> Next (g)

1

>>> Next (g)

4

>>> Next (g)

9

>>> SUM (x * * 3 for X in Xrange (10))

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) for X in range (10)}

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

>>> P

Point (x=1.0, y=2.0)

>>> p.x

1.0

>>> p.y

2.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 + q

Point (x=3.0, y=5.0)

1.21 Collection and collection operations

>>> A = {1, 2, 3, 3}

>>> A

Set ([1, 2, 3])

>>> B = {3, 4, 5, 6, 7}

>>> B

Set ([3, 4, 5, 6, 7])

>>> A | B

Set ([1, 2, 3, 4, 5, 6, 7])

>>> A & B

Set ([3])

>>> A-B

Set ([1, 2])

>>> b-a

Set ([4, 5, 6, 7])

>>> A ^ B

Set ([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])

>>> A

Counter ({2:2, 1:1})

>>> B

Counter ({2:2, 3:1})

>>> A | B

Counter ({2:2, 1:1, 3:1})

>>> A & B

Counter ({2:2})

>>> A + B

Counter ({2:4, 1:1, 3:1})

>>> A-B

Counter ({1:1})

>>> b-a

Counter ({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])

>>> A

Counter ({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])

>>> Q

Deque ([6, 5, 2, 1, 3, 4])

>>> Q.pop ()

4

>>> Q.popleft ()

6

>>> Q

Deque ([5, 2, 1, 3])

>>> Q.rotate (3)

>>> Q

Deque ([2, 1, 3, 5])

>>> Q.rotate (-3)

>>> Q

Deque ([5, 2, 1, 3])

1.25 double-ended queue with maximum length (collections.deque)

>>> Last_three = Collections.deque (maxlen=3)

>>> for I in Xrange (10):

..... last_three.append (i)

... print ', '. Join (str (x) for x in Last_three)

...

0

0, 1

0, 1, 2

1, 2, 3

2, 3, 4

3, 4, 5

4, 5, 6

5, 6, 7

6, 7, 8

7, 8, 9

1.26 dictionary sort (collections. ORDEREDDICT)

>>> m = dict ((str (x), X) for X in range (10))

>>> print ', '. Join (M.keys ())

1, 0, 3, 2, 5, 4, 7, 6, 9, 8

>>> m = collections. Ordereddict ((str (x), X) for X in range (10))

>>> print ', '. Join (M.keys ())

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

>>> m = collections. Ordereddict ((str (x), X) for X in range (10, 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):

File "<stdin>", line 1, in <module>

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)

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

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.