加入 Real Python 邮件列表后我学到的 30 个 PyTricks 技巧。
超棒的 Python
两年前我订阅了 Real Python 的邮件列表,期间学到了很多技巧和窍门。虽然这听起来可能是一种不太常见的 Python 学习方式,但我发现它非常有用。我把过去两年里学到的最有用的技巧和窍门整理成了一些笔记,今天想和大家分享一下。
1. 合并两个词典。
问题:如何合并两个词典?
答案:使用解包 **运算符。
>>> x = { 'a' : 10, 'b' : 8}
>>> x = { 'a' : 1, 'b' : 2}
>>> y = { 'b' : 3, 'c' : 4}
>>> z = { ** x, ** y}
>>> z
{ 'a' : 1, 'b' : 3, 'c' : 4}
Enter fullscreen mode
Exit fullscreen mode
2. 一种同时测试多个条件的方法。
问题:如何同时测试多个标志?
答案:使用 逗号、 any逗号 运算符而不是逗号 或运算符 。 inallorand
>>> x, y, z = 0, 1, 0
>>> if x == 1 or y == 1 or z == 1:
... print( "Passed" )
...
Passed
>>> if 1 in ( x, y, z) :
... print( "Passed" )
...
Passed
>>> if any(( x, y, z)) :
... print( "Passed" )
...
Passed
>>> x, y, z = 1, 1, 1
>>> if x == 1 and y == 1 and z == 1:
... print( "Passed" )
...
Passed
>>> if all(( x, y, z)) :
... print( "Passed" )
...
Passed
Enter fullscreen mode
Exit fullscreen mode
3. 按值对字典进行排序。
问题:如何按值对字典进行排序?
答案:使用该 sorted方法以及 operator.itemgetter任何普通函数作为键。
>>> dict1 = { 'a' : 4, 'b' : 3, 'c' : 2, 'd' : 1}
>>> dict1_sorted = dict( sorted( dict1.items() , key = lambda item:item[1]))
>>> dict1_sorted
{ 'd' : 1, 'c' : 2, 'b' : 3, 'a' : 4}
>>> import operator
>>> dict1_sorted = dict( sorted( dict1.items() , key = operator.itemgetter( 1)))
>>> dict1_sorted
{ 'd' : 1, 'c' : 2, 'b' : 3, 'a' : 4}
Enter fullscreen mode
Exit fullscreen mode
4. get字典的方法及其“default”参数。
问题:如何根据键获取字典的值?
答案:使用该 get方法。
>>> name_for_userid = { 123: "Alice" , 432: "Bob" }
>>> print( f"Hello {name_for_userid.get(123, 'there')}!" )
Hello Alice!
>>> print( f"Hello {name_for_userid.get(999, 'there')}!" )
Hello there!
Enter fullscreen mode
Exit fullscreen mode
5. 命名元组可以很好地替代手动定义类。
问:定义类还有哪些其他方法?
答案:使用 collections.namedtuple。
>>> from collections import namedtuple
>>> Car = namedtuple( 'Car' , 'color mileage' )
>>> my_car = Car( 'red' , 312.4)
>>> my_car
Car( color = 'red' , mileage = 312.4)
>>> my_car.color
'red'
>>> my_car.mileage
312.4
Enter fullscreen mode
Exit fullscreen mode
6. 很棒的 Python 导入。
问:Python 中有彩蛋吗?
答:是的。
>>> import antigravity
>>> import this
Enter fullscreen mode
Exit fullscreen mode
7. 以美观的方式打印字典。
问题:如何打印带缩进的字典?
答案:使用 json.dumps方法。
>>> import json
>>> dict1 = { 'b' : 2, 'a' : 1, 'c' : 4}
>>> print( json.dumps( dict1, indent = 4, sort_keys = True))
{
"a" : 1,
"b" : 2,
"c" : 4
}
Enter fullscreen mode
Exit fullscreen mode
8. Python 中的函数参数解包。
问题:如何一次性向给定函数传递多个参数?
答案:使用解包 *运算符。
>>> def my_func( a, b, c) :
... print( a, b, c)
...
>>> dict1 = { 'a' : 1, 'b' : 3, 'c' : 4}
>>> my_func( * dict1)
a b c
>>> my_func( ** dict1)
1 3 4
>>>
Enter fullscreen mode
Exit fullscreen mode
9. 使用内置 timeit模块来衡量代码的性能。
问题:如何测量代码的执行时间?
答案:使用该 timeit模块。
>>> import timeit
>>> code_snippet = "for _ in range(1000): ..."
>>> timeit.timeit( code_snippet, number = 10_000)
0.1994824110006448
Enter fullscreen mode
Exit fullscreen mode
10. 就地价值互换。
问题:如何在Python中交换值?
答案:使用元组表示法 ,。
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a, b
( 2, 1)
Enter fullscreen mode
Exit fullscreen mode
11. 使用“is”而不是“=”来测试对象标识。
问题:如何检验两个对象是否相同?
答案:使用 is运算符。
>>> a = [ 1, 2, 3]
>>> b = a
>>> b is a
True
Enter fullscreen mode
Exit fullscreen mode
12. Python 内置 HTTP 服务器。
问:如何预览网站?
答案:使用该 http.server方法。
➜ ~ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 ( http://0.0.0.0:8000/) ...
127.0.0.1 - - [ 08/Sep/2022 21:46:01] "GET / HTTP/1.1" 200 -
Enter fullscreen mode
Exit fullscreen mode
这将提供当前目录 http://localhost:8000或 http://127.0.0.1:8000。
13. 使用列表式阅读理解。它们更简洁,更容易阅读。
问题:如何在Python中过滤值?
答案:使用列表推导式。
# Filter odd values.
>>> a = [ x * x for x in range( 10) if not x % 2]
>>> a
[ 0, 4, 16, 36, 64]
Enter fullscreen mode
Exit fullscreen mode
14. 类型注解。
问题:如何显式声明给定变量的类型?
答案:使用类型注解。
>>> def add( a: int, b: int) -> int:
... return a + b
...
Enter fullscreen mode
Exit fullscreen mode
15. 查找可迭代对象中的最常见元素。
问题:如何找到 n可迭代对象中最频繁出现的项?
答案:使用该 collections.Counter.most_common方法。
>>> c = collections.Counter( "HelloWorld" )
>>> c
Counter({ 'l' : 3, 'o' : 2, 'H' : 1, 'e' : 1, 'W' : 1, 'r' : 1, 'd' : 1})
>>> c.most_common( 2)
[( 'l' , 3) , ( 'o' , 2)]
# they have the most counts as n=2 in this case.
Enter fullscreen mode
Exit fullscreen mode
16. 为可迭代对象生成排列。
问题:如何为给定的可迭代对象生成排列?
答案:使用该 itertools.permutations方法。
>>> import itertools
>>> for p in itertools.permutations( 'abc' ) :
... print( p)
...
( 'a' , 'b' , 'c' )
( 'a' , 'c' , 'b' )
( 'b' , 'a' , 'c' )
( 'b' , 'c' , 'a' )
( 'c' , 'a' , 'b' )
( 'c' , 'b' , 'a' )
Enter fullscreen mode
Exit fullscreen mode
17. __str__对比 __repr__。
问题:何时使用 __str__和 __repr__?
答案: __repr__是面向开发者的, __str__是面向客户的。
>>> import datetime
>>> today = datetime.datetime.utcnow()
>>> today
datetime.datetime( 2022, 9, 8, 19, 5, 39, 446208)
>>> str( today)
'2022-09-08 19:05:39.446208'
>>> repr( today)
'datetime.datetime(2022, 9, 8, 19, 5, 39, 446208)'
>>> today
datetime.datetime( 2022, 9, 8, 19, 5, 39, 446208)
Enter fullscreen mode
Exit fullscreen mode
18. 根据需要对类方法使用装饰器 @classmethod。 @staticmethod
classmethod问题:和 之间有什么区别 staticmethod?
>>> class A:
... def foo( self, x) :
... print( f"executing foo({self}, {x})" )
... @classmethod
... def class_foo( cls, x) :
... print( f"executing class_foo({cls}, {x})" )
... @staticmethod
... def static_foo( x) :
... print( f"executing static_foo({x})" )
...
>>> a = A()
Enter fullscreen mode
Exit fullscreen mode
答案:使用时 classmethod,对象实例的类会隐式地作为第一个参数传递,而不是自身。
>>> a.foo(1)
executing foo(<__main__.A object at 0x7f90ff34cf70>, 1)
Enter fullscreen mode
Exit fullscreen mode
staticmethod它们既不能访问 cls类,也不能 self访问实例。它们的行为类似于普通函数,区别在于你可以从实例或类中调用它们:
>>> a.static_foo( 1)
executing static_foo( 1)
>>> A.static_foo( 'hi' )
executing static_foo( hi)
Enter fullscreen mode
Exit fullscreen mode
19. Lambda 函数。
问题:何时使用lambda函数?
答案:用来表示某种数学函数。
>>> f = lambda x, y: x+y
>>> f( 2,3)
5
Enter fullscreen mode
Exit fullscreen mode
20. 使用 IP 地址。
问题:如何存储IP地址?
答案:使用该 ipaddress模块。
>>> import ipaddress
>>> ipaddress.ip_address( '192.168.1.2' )
IPv4Address( '192.168.1.2' )
>>> ipaddress.ip_address( '::1' )
IPv6Address( '::1' )
Enter fullscreen mode
Exit fullscreen mode
21. 在运行时访问类名和函数名。
问题:如何在运行时访问类名和函数名?
答案:使用该 __name__方法。
>>> from collections import namedtuple
>>> Car = namedtuple( 'Car' , 'color mileage' )
>>> car = Car( color = 'red' , mileage = 123.12)
>>> car.__class__.__name__
'Car'
>>>
Enter fullscreen mode
Exit fullscreen mode
22. 类继承和 issubclass内置函数。
问题:如何检查类继承关系?
答案:使用该 issubclass模块。
>>> class Parent:
... ...
...
>>> class Child( Parent) :
... ...
...
>>> issubclass( Child, Parent)
True
Enter fullscreen mode
Exit fullscreen mode
23. Unicode 变量名。
问:Python 中是否允许使用 Unicode 编码的变量名?
答:是的。
>>> á = 'a'
>>> ª = 1
>>> ❤️ = 'Python 2' # not allowed
File "<stdin>" , line 1
❤️ = 'Python 2'
^
SyntaxError: invalid character '❤️' ( U+1F4A9)
Enter fullscreen mode
Exit fullscreen mode
24. globals和 locals。
globals问题:和 之间有什么区别 locals?
答案: globals获取当前作用域内的所有全局变量。
>>> globals()
{ '__name__' : '__main__' , '__doc__' : None, '__package__' : None,
.
.
.
Enter fullscreen mode
Exit fullscreen mode
locals获取当前作用域内的所有局部变量。
>>> locals()
{ '__name__' : '__main__' , '__doc__' : None, '__package__' : None,
.
.
.
Enter fullscreen mode
Exit fullscreen mode
25. faulthandler模块。
问:它的 faulthandler作用是什么?
答案:即使 Python 崩溃或发生段错误,也要显示回溯信息。
>>> import faulthandler
>>> faulthandler.enable()
Enter fullscreen mode
Exit fullscreen mode
26. else带 for循环 while。
问题: else循环的作用是什么?
答案:它的作用域仅在循环执行完毕且未遇到 break语句时才有效。
>>> for i in range( 10) :
... print( i)
... if i == 8:
... break # termination, no else
... else :
... print( "after for loop" )
...
0
1
2
3
4
5
6
7
8
Enter fullscreen mode
Exit fullscreen mode
27. Pythonic 中检查列表中所有元素是否相等的方法。
问题:如何检查列表中的所有元素是否相等?
答案:使用该 set方法检查唯一值。
>>> lst = [ 1, 1, 1]
>>> len( set ( lst)) == 1
True
Enter fullscreen mode
Exit fullscreen mode
28 contextlib.suppress.
问题:如何忽略特定例外情况?
答案:使用该 contextlib模块。
>>> import contextlib, os
>>> with contextlib.suppress( FileNotFoundError) :
... os.remove( 'file_name.txt' )
...
>>>
Enter fullscreen mode
Exit fullscreen mode
29. 强制仅关键字参数。
问题:如何强制只使用关键字参数?
答案:使用 *运算符。
>>> def f( a, b, * , c = 'x' , d = 'y' ) :
... return "Hello"
...
>>> f( 1, 2, 'p' , 'q' )
Traceback ( most recent call last) :
File "<stdin>" , line 1, in <module>
TypeError: f() takes 2 positional arguments but 4 were given
>>> f( 1, 2, c = 'p' , d = 'q' )
'Hello'
Enter fullscreen mode
Exit fullscreen mode
30. 多组 kwargs。
问题:如何传递多组关键字参数?
答案:使用解包 **运算符。
>>> def f( a, b, c, d) :
... ...
...
>>> x = { 'a' : 1, 'b' : 2}
>>> y = { 'c' : 3, 'd' : 4}
>>> f( ** x, ** y)
>>>
Enter fullscreen mode
Exit fullscreen mode
这些都是我从订阅 Real Python 邮件列表中学到的东西。如果你想更深入地了解 Python,我强烈推荐你看看我的代码仓库;你可能会惊讶于自己能学到多少东西!
📚 超棒的 Python 资源(主要来自 PyCon)。
超棒的 Python
📜 摘要
这里精心整理了一份 Python 教程、笔记、幻灯片、PyCon 演讲相关文件以及一些值得一读的书籍清单。您可以将其用作掌握 Python 编程语言及其他相关内容(例如框架等)的参考文档。
该代码仓库主要发挥以下三个作用:
分享一份带有个人观点的Python视频列表。
分享来自优秀社区的笔记。
分享几本对提升你的 Python 技能大有裨益的书籍。
如果您想了解如何为该项目做出贡献,请参阅 Guideline。
别忘了点赞⭐按钮,点个奇数次哦 ;-)
目前由……维护 Mahmoud Harmouch。
👉 目录(TOC)。
Python 讲座 1.1. 初级 - 核心 1.2. 中级 - 核心 1.3. 通用 1.4. Python 2 和 Python 3 …
封面图片由 Gerd Altmann 提供,来自 Pixabay 。
文章来源:https://dev.to/wiseai/30-pytricks-ive-learned-by-joining-the-real-python-mailing-list-227i