这篇教程分享15 超级好用得 Python 实用技巧写得很实用,希望能帮到您。
01 all or any
Python 语言如此流行的众多原因之一,是因为它具有很好的可读性和表现力。 人们经常开玩笑说 Python 是可执行的伪代码。当你可以像这样写代码时,就很难反驳。 x = [True, True, False]if any(x): print("至少有一个True")if all(x): print("全是True")if any(x) and not all(x): print("至少一个True和一个False")
02 dir
有没有想过如何查看 Python 对象内部查看它具有哪些属性? 在命令行中输入: dir() dir("Hello World") dir(dir) 当以交互方式运行 Python 以及动态探索你正在使用的对象和模块时,这可能是一个非常有用的功能。在这里阅读更多functions 相关内容。
03 列表(list)推导式
关于 Python 编程,我最喜欢的事情之一是它的列表推导式。 这些表达式可以很容易地编写出非常顺畅的代码,几乎与自然语言一样。 numbers = [1,2,3,4,5,6,7]evens = [x for x in numbers if x % 2 is 0]odds = [y for y in numbers if y not in evens]cities = ['London', 'Dublin', 'Oslo']def visit(city): print("Welcome to "+city) for city in cities: visit(city)
04 pprint
Python 的默认print 函数完成了它的工作。但是如果尝试使用print函数打印出任何大的嵌套对象,其结果相当难看。这个标准库的漂亮打印模块pprint 可以以易于阅读的格式打印出复杂的结构化对象。 这算是任何使用非平凡数据结构的 Python 开发人员的必备品。 import requestsimport pprinturl = 'https://randomuser.me/api/?results=1'users = requests.get(url).json()pprint.pprint(users)
05 repr
在 Python 中定义类或对象时,提供一种将该对象表示为字符串的“官方”方式很有用。 例如: >>> file = open('file.txt', 'r') >>> print(file) <open file 'file.txt', mode 'r' at 0x10d30aaf0> 这使得调试代码更加容易。将其添加到你的类定义中,如下所示: class someClass: def __repr__(self): return "<some description here>"someInstance = someClass()# 打印 <some description here>print(someInstance)
06 sh
Python 是一种很棒的脚本语言。有时使用标准的 os 和 subprocess 库克可能有点头疼。 该SH库让你可以像调用普通函数一样调用任何程序 Python中优雅处理JSON文件的方法实例 基于Python实现简单的定时器详解 |