Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the hidden features of Python

2025-03-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "what are the hidden features of Python", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the hidden features of Python.

1...

Yes, you read it right, in Python. Is an effective structure. ... Is a singleton object called an ellipsis. If you type it into the Python interpreter, you can see it:

> >. Ellipsis

According to official documentation, the ellipsis is "a special value that is mainly used in conjunction with the extended slicing syntax of user-defined container data types." It has two main use cases. One is to act as a placeholder in an empty function. The other is Numpy, as a slice item, as described in the document.

Placeholder for function

Def my_awesome_function ():...

This is equivalent to:

Def my_awesome_function (): Ellipsis

And this:

Def my_awesome_function (): pass

Note that I'm not saying pass =... I'm just saying that as a function body, the result is the same. In fact, you can use anything as a placeholder.

Numpy

The following code basically means creating a matrix array. Each matrix is 3 × 3. Then get the second column of all the innermost matrices (the numpy array is based on 0).

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]]) > array [., 1] array ([[1, 4, 7], [10, 13, 16], [19, 22, 25]]) > # This is equivalent to > array [:, 1] array ([[1, 4, 7], [10, 13, 16], [19, 22, 25]) 2 an elegant unpack

Iterative unpacking is a very convenient feature that has been around for some time. Most people use it to unpack iterable objects that contain multiple items. For example, consider the following use case.

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

Or:

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

But there is a good use case that many people do not take advantage of, which is to unpack a single iterator. Why is this useful? With all due respect, it makes the code a little more elegant.

Instead of doing this:

> lst = [1] > > a = lst [0] > > a 1 > (a,) = lst > a 1

You can do this:

> lst = [1] > [a] = lst > a 1

I know it may seem silly, but at least to me, it looks more elegant.

Can you make this list lie flat?

There are several ways to flatten a list. The easiest thing to do is to use lists to understand.

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

If you prefer functional programming, you can use a reducer.

> from functools import reduce > reduce (lambda XMagery y: xonomy1) [1, 2, 3, 4, 5, 6, 7, 8, 9]

However, there is another way. You can use the sum function!

Sum (l, []) [1, 2, 3, 4, 5, 6, 7, 8, 9]

This is because the sum function iterates through each element in the list and concatenates them with the default value passed as the second parameter. Because lists in Python can be concatenated with the + operator, you get something like this:

> > sum (l, []) = > [] + [1,2,3] + [4,5,6] + [7,8,9] [1,2,3,4,5,6,7,8,9]

Clever as this technique is, it is by no means readable. Moreover, its performance is also very poor.

4else

The else statement can be used for several purposes. Few people know about it, but you can use it outside the classic "if else" block. Python allows it to be used for loops and exception blocks.

Cycle

Python has two different loops, for and while. Both can be "bad". That is, if a condition is met, you can jump out of the loop. For example:

In [7]: while a

< 10: ...: if a == 3: ...: print("a == 3. exiting loop.") ...: break ...: a += 1 ...: a == 3. exiting loop. 现在,假设我们要找一个特定的条件。如果满足该条件,则将结果保存在一个名为found的标志中。然后,如果我们没有找到它,我们打印一条消息。 found = False a = 0 while a < 10: if a == 12: found = True a += 1 if not found: print("a was never found") 因为a永远不会变成12,所以程序输出a永远不会找到。 好,但是我们在这里怎么用else呢? else可以用来替换标志。基本上,我们实际需要的是运行循环,如果没有找到,则打印一条消息。 a = 0 while a < 10: if a == 12: break a += 1 else: print("a was never found") 由于它适用于任何循环,所以您可以使用for而不是while。 for a in range(10): if a == 12: break a += 1 else: print("a was never found") 异常 Python中的else是如此通用,你甚至可以使用try…except。这里的思想是捕获异常不发生的情况。 In [13]: try: ...: {}['lala'] ...: except KeyError: ...: print("Key is missing") ...: else: ...: print("Else here") ...: Key is missing 在这个例子中,我们尝试在一个空字典中查找名为"lala"的键。由于"lala"不存在,代码将引发一个KeyError异常。当我在IPython中运行这段代码时,得到了预期的结果。 如果程序没有引发异常呢? In [14]: try: ...: {'lala': 'bla'}['lala'] ...: except KeyError: ...: print("Key is missing") ...: else: ...: print("Else here") ...: Else here 现在我们可以看到它的实际应用。{' lala ': ' bla '}[' lala ']块不会引发KeyError,所以else就起作用了。 5比较 这是我最喜欢的一个,老实说,没有那么隐蔽。与许多编程语言(如Java、C或c++)不同,Python允许链式比较运算符。假设你有一个变量x,它的值是10。现在,假设你想断言x在一个范围内,比如5..20。你可以这样做: In [16]: x = 10 In [17]: if x >

= 5 and x x = 10 > 20 = = x > 1 False > 25 > x > > x < 20 < x > 10 < 1000 True so far, I believe you have a deeper understanding of "what are the hidden features of Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report