Five hidden tricks in Python you've probably never heard of

PHPz
Release: 2023-04-13 14:31:03
forward
1583 people have browsed it

Five hidden tricks in Python you've probably never heard of

Life is short, learn Python quickly

1. ... Object

Yes, you read that right, it is "... "

In Python... represents an object named Ellipsis. According to the official description, it is a special value that can usually be used as a placeholder for an empty function or used for slicing operations in Numpy.

For example:

def my_awesome_function():
...
Copy after login

is equivalent to:

def my_awesome_function():
Ellipsis
Copy after login

Of course, you can also use pass or string as a placeholder:

def my_awesome_function():
pass
Copy after login
def my_awesome_function():
"An empty, but also awesome function"
Copy after login

Their final The effects are the same.

Next let’s talk about... how objects work in Numpy. Create a 3x3x3 matrix array, and then get the second column of all innermost matrices:

>>> import numpy as np
>>> array = np.arange(27).reshape(3, 3, 3)
>>> array
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
 [[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
 [[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
Copy after login

In order to get the second column of the top-level matrix, the traditional method may be like this:

>>> array[:, :, 1]
array([[ 1, 4, 7],
 [10, 13, 16],
 [19, 22, 25]])
Copy after login

If you can use... object, it is like this:

>>> array[..., 1]
array([[ 1, 4, 7],
 [10, 13, 16],
 [19, 22, 25]])
Copy after login

But please note that . .. objects only work with Numpy, not Python built-in arrays.

2. Decompression of iteration objects

Decompression of iteration objects is a very convenient feature:

>>> a, *b, c = range(1, 11)
>>> a
1
>>> c
10
>>> b
[2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

or:

>>> a, b, c = range(3)
>>> a
0
>>> b
1
>>> c
2
Copy after login

Similarly, instead of writing like this Code:

>>> lst = [1]
>>> a = lst[0]
>>> a
1
>>> (a, ) = lst
>>> a
1
Copy after login

You might as well perform a more elegant assignment operation like decompressing the iteration object:

>>> lst = [1]
>>> [a] = lst
>>> a
1
Copy after login

Although this seems a bit stupid, in my personal opinion, it is worse than the previous one The writing is more elegant.

3. The Art of Expansion

There are various strange ways to expand arrays, for example:

>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> flattened = [elem for sublist in l for elem in sublist]
>>> flattened
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

If you have a certain understanding of reduce and lambda, it is recommended to use more elegant Method:

>>> from functools import reduce
>>> reduce(lambda x,y: x+y, l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

The combination of reduce and lambda can perform splicing operations on each sub-array in the l array.

Of course, there is a more magical way:

>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> # 其实相当于 [] + [1, 2, 3] + [4, 5, 6] + [7, 8, 9]
Copy after login

Yes, by performing sum operation on the two-dimensional array, you can "add" each element in the two-dimensional array. Piece it together.

In the same way, if you perform a sum operation on a three-digit array, it can be transformed into a two-dimensional array. At this time, if you perform a sum operation on the two-dimensional array, it can be expanded into a one-dimensional array.

Although this technique is excellent, I don’t recommend it because the readability is too poor.

4. Underscore_ variable

Whenever you run an expression in the Python interpreter, IPython, or Django Console, Python will bind the output value to the _ variable:

>>> nums = [1, 3, 7]
>>> sum(nums)
11
>>> _
11
>>>
Copy after login

Since it is a variable, you can overwrite it at any time, or operate it like a normal variable:

>>> 9 + _
20
>>> a = _
>>> a
20
Copy after login

5. Multiple uses of else

Many people don’t know , else can be used in many places. In addition to the typical if else, we can also use it in loops and exception handling.

Loop

If you need to determine whether a certain logic is processed in the loop, this is usually done:

found = False
a = 0
while a < 10:
if a == 12:
found = True
a += 1
if not found:
print("a was never found")
Copy after login

If else is introduced, we can use one less variable:

a = 0
while a < 10:
if a == 12:
break
a += 1
else:
print("a was never found")
Copy after login

Exception handling

We can use else in try...except... to write the logic when the exception is not caught:

In [13]: try:
...: {}['lala']
...: except KeyError:
...: print("Key is missing")
...: else:
...: print("Else here")
...:
Key is missing
Copy after login

In this way, if the program does not Exception, the else branch will be taken:

In [14]: try:
...: {'lala': 'bla'}['lala']
...: except KeyError:
...: print("Key is missing")
...: else:
...: print("Else here")
...:
Else here
Copy after login

If you often do exception handling, you will know that this technique is quite convenient.

The above is the detailed content of Five hidden tricks in Python you've probably never heard of. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!