Home > Backend Development > Python Tutorial > 30 Python language features and tricks you may not know

30 Python language features and tricks you may not know

高洛峰
Release: 2016-10-19 11:38:00
Original
1099 people have browsed it

Ever since I started learning Python I decided to maintain a list of "tricks" that I use frequently. Whenever I see a piece of code that makes me think "Cool, this works!" (in an example, on StackOverflow, in open source software, etc.), I try it until I understand it, and then Add it to the list. This post is part of a cleaned up list. If you are an experienced Python programmer, although you may already know some, you may still discover some you don't know. If you are a C, C++, or Java programmer who is learning Python, or just starting to learn programming, then you will find many of them very useful like I did.

Each trick or language feature can only be verified through examples without excessive explanation. While I've tried to make the examples clear, some of them will still look a little complicated, depending on your familiarity. So if you're not sure after looking at the example, the title can provide enough information for you to get the detailed content through Google.

The list is sorted by difficulty, with commonly used language features and techniques at the front.

1.30 Maximum and minimum elements (heapq.nlargest and heapq.nsmallest)

>>> a = [random.randint(0, 100) for __ in xrange(100)]

>>> heapq.nsmallest(5, a)

[3, 3, 5, 6, 8]

>>> 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 itertools.product([0, 1], repeat=4):

... print '.join(str(x) for

0111

1000

1001

1010

1011

1100

1101

1110

1111

1.32 Combinations and replacements (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)

...

123

124

125

134

print ''.join( str(x)for >> for p in itertools .permutations([1, 2, 3, 4]):

... print ''.join(str(x) for x in p)

...

1234

1243

1324

3124

3142

3214

3241

3412

3421

4123

4132

4213

4231

4312

4321

1.34 Link iteration (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 Group 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 print_data(rows):

... print 'n'.join('t'.join('{:

...

>>> print_data(data)

young               myope                   no                      reduced                 none  

young               myope                   no                      normal                  soft  

young               myope                   yes                     reduced                 none  

young               myope                   yes                     normal                  hard  

young               hypermetrope            no                      reduced                 none  

young               hypermetrope            no                      normal                  soft  

young               hypermetrope            yes                     reduced                 none  

young               hypermetrope            yes                     normal                  hard  

pre-presbyopic      myope                   no                      reduced                 none  

pre-presbyopic      myope                   no                      normal                  soft  

pre-presbyopic      myope                   yes                     reduced                 none  

pre-presbyopic      myope                   yes                     normal                  hard  

pre-presbyopic      hypermetrope            no                      reduced                 none  

pre-presbyopic      hypermetrope            no                      normal                  soft  

pre-presbyopic      hypermetrope            yes                     reduced                 none  

pre-presbyopic      hypermetrope            yes                     normal                  none  

presbyopic          myope                   no                      reduced                 none  

presbyopic          myope                   no                      normal                  none  

presbyopic          myope                   yes                     reduced                 none  

presbyopic          myope                   yes                     normal                  hard  

presbyopic          hypermetrope            no                      reduced                 none  

presbyopic          hypermetrope            no                      normal                  soft  

presbyopic          hypermetrope            yes                     reduced                 none  

presbyopic          hypermetrope            yes                     normal                  none  

 

>>> data.sort(key=itemgetter(-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                      reduced                 none  

young               myope                   yes                     reduced                 none  

young               hypermetrope            no                      reduced                 none  

young               hypermetrope            yes                     reduced                 none  

pre-presbyopic      myope                   no                      reduced                 none  

pre-presbyopic      myope                   yes                     reduced                 none  

pre-presbyopic      hypermetrope            no                      reduced                 none  

pre-presbyopic      hypermetrope            yes                     reduced                 none  

pre-presbyopic      hypermetrope            yes                     normal                  none  

presbyopic          myope                   no                      reduced                 none  

presbyopic          myope                   no                      normal                  none  

presbyopic          myope                   yes                     reduced                 none  

presbyopic          hypermetrope            no                      reduced                 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 


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template