35 Python Programming Tips

Source: Internet
Author: User
When I started learning python, I began to summarize a collection of python tips. Later, when I saw a piece of cool code in StackOverflow or an open-source software, I was surprised that I could do this again !, At that time, I will try my best to make a public debut of this blog. If you are already a python guru, you should know most of the usage here, but I think you should be able to find some new tips that you don't know. If you were a c, c ++, and java programmer, and you are learning python at the same time, or you are just a beginner in programming, then you will see a lot of useful practical skills that can surprise you, just as I did at the beginning.

Every technique and language usage will be presented to you in an example, without any additional instructions. I have tried my best to make every example easy to understand, but readers may still have some obscure points because of their different familiarity with python. So if these examples cannot be understood by you, at least the title of this example will help you when you go to google search.

The entire set is probably sorted by difficulty level. simplicity is common at the beginning and rarely at the end.

1.1 binning

The code is as follows:


>>> A, B, c = 1, 2, 3
>>> A, B, c
(1, 2, 3)
>>> A, B, c = [1, 2, 3]
>>> A, B, c
(1, 2, 3)
>>> 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]
>>>
1
>>> B
2
>>> C
3
>>> D
4


1.2 binning variable exchange

The code is as follows:

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


1.3 extension unpacking (only compatible with python3)

The code is as follows:

>>> A, * B, c = [1, 2, 3, 4, 5]
>>>
1
>>> B
[2, 3, 4]
>>> C
5


1.4 Negative index

The code is as follows:

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


1.5 cut list

The code is as follows:

>>> 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 cutting list

The code is as follows:

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


1.7 specified step cut list

The code is as follows:

>>> 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]
>>> A [2: 8]
[2, 4, 6]


1.8 negative step cut list

The code is as follows:

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

The code is as follows:

>>> A = [1, 2, 3, 4, 5]
>>> A [2: 3] = [0, 0]
>>>
[1, 2, 0, 0, 4, 5]
>>> A [1:1] = [8, 9]
>>>
[1, 8, 9, 2, 0, 0, 4, 5]
>>> A [1:-1] = []
>>>
[1, 5]


1.10 naming list cutting method

The code is as follows:

>>> A = [0, 1, 2, 3, 4, 5]
>>> LASTTHREE = slice (-3, None)
>>> LASTTHREE
Slice (-3, None, None)
>>> A [LASTTHREE]
[3, 4, 5]


1.11 List and iterator compression and decompression

The code is as follows:

>>> 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 adjacent element compressors

The code is as follows:

>>> 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_adjacent (a, 2)
[(1, 2), (3, 4), (5, 6)]
>>> Group_adjacent (a, 1)
[(1,), (2,), (3,), (4,), (5,), (6,)]


1.13 sliding value windows with compressors and Iterators in the list

The code is as follows:

>>> 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 reverse dictionary with a compressed file

The code is as follows:

>>> 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 expand the list

The code is as follows:

>>> A = [[1, 2], [3, 4], [5, 6]
>>> List (itertools. chain. from_iterable ())
[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 ()
[1, 2, 3, 4, 5, 6, 7, 8]


1.16 generator expression

The code is as follows:

>>> 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 (10) if x % 3 = 1)
408


1.17 dictionary derivation

The code is as follows:

>>> 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 use a dictionary to derive a reverse dictionary

The code is as follows:

>>> 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 name tuples

The code is as follows:

>>> 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 inherit the name tuples

The code is as follows:

>>> 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 operation set

The code is as follows:

>>> A = {1, 2, 3, 3}
>>>
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-
Set ([4, 5, 6, 7])
>>> A ^ B
Set ([1, 2, 4, 5, 6, 7])
>>> (A ^ B) = (A-B) | (B-))
True


1.22 multiple sets of operations

The code is as follows:

>>> A = collections. Counter ([1, 2, 2])
>>> B = collections. Counter ([2, 2, 3])
>>>
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-
Counter ({3: 1 })


1.23 measure the most common elements in the iteratable.

The code is as follows:

>>> A = collections. Counter ([1, 1, 2, 2, 3, 3, 3, 4, 5, 6, 7])
>>>
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 queues that can be operated on both ends

The code is as follows:

>>> 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 dual-end queue with maximum length

The code is as follows:

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

The code is as follows:

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

The code is as follows:

>>> M = dict ()
>>> M ['A']
Traceback (most recent call last ):
File" ", Line 1, in
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 expression of default dictionary

The code is as follows:

>>> Import json
>>> Tree = lambda: collections. defaultdict (tree)
>>> Root = tree ()
>>> Root ['menu '] ['id'] = 'file'
>>> Root ['menu '] ['value'] = 'file'
>>> Root ['menu '] ['menitems'] ['new'] ['value'] = 'new'
>>> Root ['menu '] ['menitems'] ['new'] ['onclick'] = 'new ();'
>>> Root ['menu '] ['menitems'] ['open'] ['value'] = 'open'
>>> Root ['menu '] ['menitems'] ['open'] ['onclick'] = 'Open ();'
>>> Root ['menu '] ['menitems'] ['close'] ['value'] = 'close'
>>> Root ['menu '] ['menitems'] ['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 mappings between objects and unique counts

The code is as follows:

>>> 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 the largest and smallest list elements

The code is as follows:

>>> A = [random. randint (0,100) for _ in xrange (100)]
>>> Heapq. nsmallest (5,)
[3, 3, 5, 6, 8]
>>> Heapq. nlargest (5,)
[100,100, 99, 98, 98]


1.31 Cartesian product of two lists

The code is as follows:

>>> 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 itertools. product ([0, 1], repeat = 4 ):
... Print ''. join (str (x) for x in p)
...
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111


1.32 list combination and list element substitution combination

The code is as follows:

>>> For c in itertools. combinations ([1, 2, 3, 4, 5], 3 ):
... Print ''. join (str (x) for x in c)
...
123
124
125
134
135
145
234
235
245
345
>>> For c in itertools. combinations_with_replacement ([1, 2, 3], 2 ):
... Print ''. join (str (x) for x in c)
...
11
12
13
22
23
33


1.33 List element arrangement and combination

The code is as follows:

>>> For p in itertools. permutations ([1, 2, 3, 4]):
... Print ''. join (str (x) for x in p)
...
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321


1.34 connectable iterator

The code is as follows:

>>> 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 specify column clustering based on the file

The code is as follows:

>>> 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'. join ('{:< 16}'. format (s) for s in row) for row in rows)
...

>>> Print_data (data)
Young myope no supported CED none
Young myope no normal soft
Young myope yes reduced none
Young myope yes normal hard
Young hypermetrope no supported CED none
Young hypermetrope no normal soft
Young hypermetrope yes reduced none
Young hypermetrope yes normal hard
Pre-presbyopic myope no supported CED none
Pre-presbyopic myope no normal soft
Pre-presbyopic myope yes already CED none
Pre-presbyopic myope yes normal hard
Pre-presbyopic hypermetrope no supported CED none
Pre-presbyopic hypermetrope no normal soft
Pre-presbyopic hypermetrope yes already CED none
Pre-presbyopic hypermetrope yes normal none
Presbyopic myope no supported CED none
Presbyopic myope no normal none
Presbyopic myope yes reduced none
Presbyopic myope yes normal hard
Presbyopic hypermetrope no supported CED none
Presbyopic hypermetrope no normal soft
Presbyopic hypermetrope yes reduced none
Presbyopic hypermetrope yes normal none

>>> Data. sort (key = lambda r: r [-1])
>>> For value, group in itertools. groupby (data, lambda r: r [-1]):
... Print '-----------'
... Print 'group: '+ value
... Print_data (group)
...
-----------
Group: hard
Young myope yes normal hard
Young hypermetrope yes normal hard
Pre-presbyopic myope yes normal hard
Presbyopic myope yes normal hard
-----------
Group: none
Young myope no supported CED none
Young myope yes reduced none
Young hypermetrope no supported CED none
Young hypermetrope yes reduced none
Pre-presbyopic myope no supported CED none
Pre-presbyopic myope yes already CED none
Pre-presbyopic hypermetrope no supported CED none
Pre-presbyopic hypermetrope yes already CED none
Pre-presbyopic hypermetrope yes normal none
Presbyopic myope no supported CED none
Presbyopic myope no normal none
Presbyopic myope yes reduced none
Presbyopic hypermetrope no supported CED none
Presbyopic hypermetrope yes reduced none
Presbyopic hypermetrope yes normal none
-----------
Group: soft
Young myope no normal soft
Young hypermetrope no normal soft
Pre-presbyopic myope no normal soft
Pre-presbyopic hypermetrope no normal soft
Presbyopic hypermetrope no normal soft

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.