This is not only the first sentence of “The Zen of Python”, but also the creed for all Python developers. 这不仅是《Python 禅》的第一句话,也是所有 Python 开发者的信条。
But how to distinguish between beautiful and ugly code? 但如何区分代码的美丑呢?
More importantly, how to write beautiful Python code? 更重要的是,如何编写漂亮的 Python 代码?
Talk is cheap. This article will demonstrate 9 fabulous Python tricks with beginner-friendly examples to help you write more Pythonic programs in your daily work. 空谈误国。本文将以初学者易懂的示例演示 9 个 Python 绝妙技巧,帮助你在日常工作中编写更多 Python 程序。
1. Avoid Nested Python Loops Using product() Function 1.使用 product() 函数避免嵌套的 Python 循环
When a program becomes complicated, you inevitably have to write nested loops. However, nested loops will make programs harder to read and maintain. 当程序变得复杂时,就不可避免地要编写嵌套循环。然而,嵌套循环会增加程序的阅读和维护难度。
Fortunately, you can always avoid nested loops in Python through the built-in product() function. 幸运的是,在 Python 中,您可以通过内置的 product() 函数避免嵌套循环。
For example, we have a program as follows which contains 3-level nested for loops: 例如,我们有一个包含 3 层嵌套 for 循环的程序如下:
To make it neater and cleaner, we can use the product() function, which is from the itertools module, to optimise the code: 为了使代码更简洁明了,我们可以使用 itertools 模块中的 product() 函数来优化代码:
2. Walrus Operator: A Cute Trick for Assignment Expressions 2.海象操作符赋值表达式的可爱技巧
Since Python 3.8, there is a new syntax called “walrus operator” that can assign values to variables as part of a larger expression. 自 Python 3.8 起,有了一种名为 "walrus 操作符 "的新语法,它可以作为较大表达式的一部分为变量赋值。
The operator := got its cute name from the eyes and tusks of a walrus. 操作员 := 的可爱名字来自海象的眼睛和獠牙。
This syntax is very easy to understand. For instance, if we would like to write the following two lines of Python code in one line, how to do it? 这种语法非常容易理解。例如,如果我们想用一行代码写出下面两行 Python 代码,该怎么做呢?
author = "Yang"print(author)
# Yang
Unfortunately, we cannot directly put the assignment into the print() function. There will be a TypeError if we try it: 遗憾的是,我们不能直接在 print() 函数中进行赋值。如果我们尝试这样做,将会出现 TypeError:
print(author="Yang")
# TypeError: 'author' is an invalid keyword argument for print()
Thanks to the walrus operator, we can really do this in one line: 多亏了海象操作符,我们真的可以在一行中完成这些操作:
print(author:="Yang")
# Yang
3. Ternary Conditional Operator: Writing a Simple If-Else Structure in One Line 3.三元条件操作符在一行中编写简单的 If-Else 结构
The if-else conditions are everywhere in the programming world. To make simple logic easy to express, Python provides us with the ternary operator. Simply put, it just allows as put an if-else condition in one line: 在编程世界中,if-else 条件无处不在。为了让简单的逻辑表达变得容易,Python 为我们提供了三元运算符。简单地说,它允许在一行中写入 if-else 条件:
min = a if a < b else b
Obviously, the above code is much neater than the following: 显然,上面的代码要比下面的整洁得多:
if a<b:
min = a
else:
min = b
4. Using Lambda Functions To Define Simple Functions 4.使用 Lambda 函数定义简单函数
If you only want to define a simple function, probably you don’t need to use the traditional syntax for it. The lambda function is a more elegant option. 如果您只想定义一个简单的函数,那么您可能不需要使用传统的语法。lambda 函数是一种更优雅的选择。
For example, the following function is to calculate the Fibonacci numbers: 例如,以下函数用于计算斐波那契数字:
deffib(x):
if x<=1:
return x
else:
return fib(x-1) + fib(x-2)
It works perfectly but the code itself is a bit ugly. Let’s write a one-liner to implement the same function: 它可以完美运行,但代码本身有点难看。让我们编写一个单行代码来实现同样的功能:
5. List Comprehensions: Get a List in a Pythonic Way 5.列表理解:用毕式方法获取列表
To say the list comprehension makes your code elegant is still an understatement. It can save you lots of typing and time but still keep your code readable. Few programming languages can do this. 如果说列表理解能让你的代码变得优雅,那还只是一种轻描淡写的说法。它可以为你节省大量的键入和时间,但仍能保持代码的可读性。很少有编程语言能做到这一点。
Feel free to enjoy the above elegant program for a while and think about how many lines of code you need to write without the list comprehension trick. 请随意欣赏一下上述优雅的程序,想想如果没有列表理解技巧,你需要写多少行代码。
6. Leveraging the Higher-Order Functions in Python 6.利用 Python 中的高阶函数
Python has some built-in higher-order functions that give us the convenience to write some common logic. Python 有一些内置的高阶函数,为我们编写一些常用逻辑提供了方便。
For example, the map() function is a famous and frequently-used higher-order function. It receives two parameters, one is a function and the other is an iterable. Executing the map function will apply the function to each element of the iterable. 例如,map() 函数是一个著名的、经常使用的高阶函数。它接收两个参数,一个是函数,另一个是可迭代元素。执行 map 函数将对可迭代的每个元素应用该函数。
As the above example shows, with the help of the map() function, we can avoid writing a for loop to capitalize every word in the names list. 如上例所示,在 map() 函数的帮助下,我们可以避免编写 for 循环来对姓名列表中的每个单词进行大写。
Another famous higher-order function is reduce(). As its name implies, it applies a function into an iterable and does the cumulative operation for it. 另一个著名的高阶函数是 reduce()。顾名思义,它将一个函数应用到一个可迭代函数中,并对其进行累加操作。
For instance, the following example converts a list into one string: 例如,下面的示例将一个列表转换为一个字符串:
7. Union Operators: The Easiest Way To Merge Dictionaries 7.联合运算符:合并词典的最简单方法
Merging dictionaries is a common requirement in daily Python programming. There are many ways to do it. But all of them were ugly before Python 3.9. 合并字典是日常 Python 编程中的常见需求。有很多方法可以做到这一点。但在 Python 3.9 之前,所有这些方法都很难看。
Since Python 3.9, we finally got the most elegant way for dictionary merging — using union operators. 从 Python 3.9 开始,我们终于有了最优雅的字典合并方式--使用 union 操作符。
As the above example shows, we can simply use the | operator to merge the two different dictionaries. Even more, it also supports in-place merging: 如上例所示,我们只需使用 | 操作符即可合并两个不同的字典。此外,它还支持就地合并:
8. F-Strings: The Pythonic String Formatting Technique 8.F 字符串:Pythonic 字符串格式化技术
Almost every programming language supports string formatting syntax. But not each one is as elegant as Python’s f-string technique. 几乎所有编程语言都支持字符串格式化语法。但并不是每一种都能像 Python 的 f-string 技术一样优雅。
As the above program displays, using the f-string trick, we can apply a Python variable and define its format specifications inside an f-string. 正如上面的程序所示,使用 f-string 技巧,我们可以应用一个 Python 变量,并在 f-string 中定义其格式规范。
Can you remember the string formatting syntax of the C programming language? Do you agree that Python’s f-string syntax is much simpler? 🌞 您还记得 C 编程语言的字符串格式化语法吗?您是否同意 Python 的 f-string 语法要简单得多?🌞
“Simple is better than complex.” — The Zen of Python "简单胜于复杂"。- Python 的禅宗
What makes the f-string technique more stunning is that we can embed expressions inside f-strings. The embed expressions will be evaluated at run time. 使 f-string 技术更令人惊叹的是,我们可以在 f-string 中嵌入表达式。嵌入的表达式将在运行时进行评估。
The following example will print the time of today with the help of an f-string: 下面的示例将借助 f 字符串打印今天的时间:
9. Using Asterisks for Unpacking Iterables and Destructuring Assignments 9.使用星号解包迭代表和重构赋值
How to merge a list, a tuple and a set into one list? 如何将列表、元组和集合合并为一个列表?
The most elegant way is using asterisks: 最优雅的方法是使用星号:
A = [1, 2, 3]
B = (4, 5, 6)
C = {7, 8, 9}
L = [*A, *B, *C]
print(L)
# [1, 2, 3, 4, 5, 6, 8, 9, 7]
As stated above, the asterisks can be used as prefixes of iterables to unpack their items. 如上所述,星号可用作迭代表的前缀,以解压缩其项目。
Besides unpacking iterables, the asterisks can also be used for destructuring assignments in Python: 除了解包迭代表,星号还可用于 Python 中的重构赋值:
a, *mid, b = [1, 2, 3, 4, 5, 6]
print(a, mid, b)
# 1 [2, 3, 4, 5] 6
As shown above, with the help of one asterisk, the mid variable receives the items in the middle as a list. 如上图所示,在一个星号的帮助下,mid 变量以列表的形式接收中间的项目。
Thanks for reading. ❤️ 感谢您的阅读。❤️
Join Medium through my referral link to access millions of great articles: 通过我的推荐链接加入 Medium,获取数百万篇精彩文章: