Home  >  Article  >  Backend Development  >  21 Python Tips

21 Python Tips

WBOY
WBOYOriginal
2016-08-08 09:29:07873browse

When I started learning python, I began to summarize a collection of python tips by myself. Later, when I saw a piece of cool code on Stack Overflow

or in some open source software, I was surprised: It turns out that this can still be done! , at that time, I would try my best to try this code myself. After I understood its overall idea, I would add this code to my collection. This blog is actually the public debut of the final part of this collection. If you are already a python expert, then basically you should know most of the usages here, but I think you should also be able to discover some new tricks that you don't know. And if you were a C, C++, Java programmer and are learning Python at the same time, or are simply a novice who has just learned programming, then you should see many practical tips that are particularly useful and surprising to you, like I was the same as before.

Every technique and language usage will be shown to everyone in an example, and no other explanation is needed. I have tried my best to make each example easy to understand, but because readers have different levels of familiarity with Python, there may still be some obscure parts. So if the examples themselves don't make sense to you, at least the title of the example will help you when you google them later.

The entire collection is roughly sorted by difficulty, with simple and common ones at the front and rarer ones at the end.

1.1 Unboxing

>>> 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 b, c), d = [1, (2, 3), 4]

>>> a

1

>>> b

2

>>> c

3

>>> d

4

1.2 Unboxing variable exchange

>>> a, b = 1, 2

>>> a, b = b, a

>>> a, b

(2, 1)

1.3 extended unboxing (only compatible with python3)

>>> a, *b, c = [1, 2, 3, 4, 5]

>>> a

1

>>> b

[2, 3, 4]

>>> c

5

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 Specify step size cutting 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]

>> ;> a[2:8:2]

[2, 4, 6]

1.8 negative step size cutting 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 cutting assignment

>>> a = [1, 2, 3, 4, 5]

>>> a[2:3] = [0, 0]

>>> a

[1, 2, 0, 0, 4, 5]

>>> a[1:1] = [8, 9]

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

>>> LASTTHREE

slice(-3, None, None )

>>> a[LASTTHREE]

[3, 4, 5]

1.11 Compression and decompression of lists and 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 adjacent element compressor

>>> 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 Use compressors and iterators to slide the value window 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 Reverse dictionary with 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 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]

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(10) 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) 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 dictionary derivation to reverse the 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 tuples

>>> Point = collections.namedtuple('Point', ['x', 'y'])

>>> p = Point( x=1.0, y=2.0)

>>>

2.0

1.20 Inherit 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 + q

Point (x=3.0, y=5.0)

1.21 Operation set

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

>>> A

set([1, 2 , 3])

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

>>> B

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

>>> A | Consult the official website customer service: http://www.lampbrother.net

PHPCMS secondary development http://yun.itxdl.cn/online/phpcms/index.php?u=5

WeChat development http://yun. itxdl.cn/online/weixin/index.php?u=5

Mobile Internet server-side development http://yun.itxdl.cn/online/server/index.php?u=5

Javascript course http://yun.itxdl.cn/online/js/index.php?u=5

CTO training camp http://yun.itxdl.cn/online/cto/index.php?u=5

The above introduces 21 tips about Python, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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
Previous article:FlightNext article:Flight