用这10个小技巧加速Python编程
点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达
编码很有趣,而Python编码更有趣,因为有很多不同的方法可以实现相同的功能。但是,大多数时候都有一些首选的实现方法,有些人将其称为Pythonic。这些Pythonic的共同特征是实现的代码简洁明了。
1.负索引
人们喜欢使用序列,因为当我们知道元素的顺序,我们就可以按顺序操作这些元素。在Python中,字符串、元组和列表是最常见的序列数据类型。我们可以使用索引访问单个项目。与其他主流编程语言一样,Python支持基于0的索引,在该索引中,我们在一对方括号内使用零访问第一个元素。此外,我们还可以使用切片对象来检索序列的特定元素,如下面的代码示例所示。
# Positive Indexing
1, 2, 3, 4, 5, 6, 7, 8] numbers = [
"First Number:", numbers[0]) print(
"First Four Numbers:", numbers[:4]) print(
"Odd Numbers:", numbers[::2]) print(
...
First Number: 1
First Four Numbers: [1, 2, 3, 4]
Odd Numbers: [1, 3, 5, 7]
但是,Python通过支持负索引而进一步走了一步。具体来说,我们可以使用-1来引用序列中的最后一个元素,并向后计数。例如,最后一个元素的索引为-2,依此类推。重要的是,负索引也可以与切片对象中的正索引一起使用。
# Negative Indexing
100, 50, 4) data_shape = (
"John", "Aaron", "Mike", "Danny"] names = [
"Hello World!" hello =
...
-1]) print(data_shape[
-3:-1]) print(names[
1:-1:2]) print(hello[
...
4
['Aaron', 'Mike']
el ol
2.检查容器是否为空
if len(some_list) > 0:
# do something here when the list is not empty
else:
# do something else when the list is empty
>>> def check_container_empty(container):
... if container:
... print(f"{container} has elements.")
... else:
... print(f"{container} doesn't have elements.")
...
... check_container_empty([1, 2, 3])
... check_container_empty(set())
... check_container_empty({"zero": 0, "one": 1})
... check_container_empty(tuple())
...
[1, 2, 3] has elements.
set() doesn't have elements.
{'zero': 0, 'one': 1} has elements.
() doesn't have elements.
3.使用Split()创建字符串列表
# List of strings
# The typical way
'name', 'age', 'gender', 'address', 'account_type'] columns = [
"* Literals:", columns) print(
...
# Do this instead
'name age gender address account_type'.split() columns =
"* Split with spaces:", columns) print(
...
# If the strings contain spaces, you can use commas instead
'name, age, gender, address, account type'.split(', ') columns =
"* Split with commas:", columns) print(
...
* Literals: ['name', 'age', 'gender', 'address', 'account_type']
* Split with spaces: ['name', 'age', 'gender', 'address', 'account_type']
* Split with commas: ['name', 'age', 'gender', 'address', 'account type']
4.三元表达
# The typical way
if score > 90:
reward = "1000 dollars"
else:
reward = "500 dollars"
# Do this instead
reward = "1000 dollars" if score > 90 else "500 dollars"
# Another possible scenario
# You got a reward amount from somewhere else, but don't know if None/0 or not
reward = reward_known or "500 dollars"
# The above line of code is equivalent to below
reward = reward_known if reward_known else "500 dollars"
5.带文件对象的语句
# Create a text file that has the text: Hello World!
...
# Open the file and append some new data
"hello_world.txt", "a") text_file0 = open(
"Hello Python!") text_file0.write(
...
# Open the file again for something else
"hello_world.txt") text_file1 = open(
print(text_file1.read())
...
Hello World!
>>> with open("hello_world.txt", "a") as file:
... file.write("Hello Python!")
...
... with open("hello_world.txt") as file:
... print(file.read())
...
... print("Is file close?", file.closed)
...
Hello World!Hello Python!Hello Python!
Is file close? True
6.评估多个条件
# Multiple Comparisons
# The typical way
if a < 4 and a > 1:
# do something here# Do this instead
if 1 < a < 4:
# do somerthing here
# The typical way
if b == "Mon" or b == "Wed" or b == "Fri" or b == "Sun":
# do something here# Do this instead, you can also specify a tuple ("Mon", "Wed", "Fri", "Sun")
if b in "Mon Wed Fri Sun".split():
# do something here
# The typical ways
if a < 10 and b > 5 and c == 4:
# do somethingif a < 10 or b > 5 or c == 4:
# do something# Do these instead
if all([a < 10, b > 5, c == 4]):
# do somethingif any([a < 10, b > 5, c == 4]):
# do something
7.在函数声明中使用默认值
# The original form:
def generate_plot(data, image_name):
"""This function creates a scatter plot for the data"""
# create the plot based on the data
...
if image_name:
# save the image
...# In many cases, we don't need to save the image
generate_plot(data, None)# The one with a default value
def generate_plot(data, image_name=None):
pass# Now, we can omit the second parameter
generate_plot(data)
8.使用计数器进行元素计数
'an', 'boy', 'girl', 'an', 'boy', 'dog', 'cat', 'Dog', 'CAT', 'an','GIRL', 'AN', 'dog', 'cat', 'cat', 'bag', 'BAG', 'BOY', 'boy', 'an'] words = [
for x in set(words)} unique_words = {x.lower()
for word in unique_words:
f"* Count of {word}: {words.count(word)}") print(
...
* Count of cat: 3
* Count of bag: 1
* Count of boy: 3
* Count of dog: 2
* Count of an: 5
* Count of girl: 1
from collections import Counter
...
for x in words) word_counter = Counter(x.lower()
"Word Counts:", word_counter) print(
...
Word Counts: Counter({'an': 5, 'boy': 4, 'cat': 4, 'dog': 3, 'girl': 2, 'bag': 2})
# Find out the most common item
"Most Frequent:", word_counter.most_common(1)) print(
Most Frequent: [('an', 5)]
# Find out the most common 2 items
"Most Frequent:", word_counter.most_common(2)) print(
Most Frequent: [('an', 5), ('boy', 4)]
9.按不同的订单要求排序
# A list of numbers and strings
1, 3, 7, 2, 5, 4] numbers = [
'yay', 'bill', 'zen', 'del'] words = [
# Sort them
print(sorted(numbers))
print(sorted(words))
...
[1, 2, 3, 4, 5, 7]
['bill', 'del', 'yay', 'zen']
# Sort them in descending order
True)) print(sorted(numbers, reverse=
True)) print(sorted(words, reverse=
...
[7, 5, 4, 3, 2, 1]
['zen', 'yay', 'del', 'bill']
# Create a list of tuples
'John', 95), ('Aaron', 99), ('Zack', 97), ('Don', 92), ('Jennifer', 100), ('Abby', 94), ('Zoe', 99), ('Dee', 93)] grades = [(
# Sort by the grades, descending
lambda x: x[1], reverse=True) sorted(grades, key=
[('Jennifer', 100), ('Aaron', 99), ('Zoe', 99), ('Zack', 97), ('John', 95), ('Abby', 94), ('Dee', 93), ('Don', 92)]
# Sort by the name's initial letter, ascending
lambda x: x[0][0]) sorted(grades, key=
[('Aaron', 99), ('Abby', 94), ('Don', 92), ('Dee', 93), ('John', 95), ('Jennifer', 100), ('Zack', 97), ('Zoe', 99)]
# Requirement: sort by name initial ascending, and by grades, descending
# Both won't work
lambda x: (x[0][0], x[1]), reverse=True) sorted(grades, key=
[('Zoe', 99), ('Zack', 97), ('Jennifer', 100), ('John', 95), ('Dee', 93), ('Don', 92), ('Aaron', 99), ('Abby', 94)]
lambda x: (x[0][0], x[1]), reverse=False) sorted(grades, key=
[('Abby', 94), ('Aaron', 99), ('Don', 92), ('Dee', 93), ('John', 95), ('Jennifer', 100), ('Zack', 97), ('Zoe', 99)]
# This will do the trick
lambda x: (x[0][0], -x[1])) sorted(grades, key=
[('Aaron', 99), ('Abby', 94), ('Dee', 93), ('Don', 92), ('Jennifer', 100), ('John', 95), ('Zoe', 99), ('Zack', 97)]
10.不要忘记defaultdict
'name': "John", 'age': 18} > student = {
... student['gender']
...
Traceback (most recent call last):
File "<input>", line 2, in <module>
KeyError: 'gender'
"a", "a", "c", "d", "d", "c", "a", "b"] letters = [
final_dict = {}
for letter in letters:
if letter not in final_dict:
final_dict[letter] = []
final_dict[letter].append(letter)
...
"Final Dict:", final_dict) print(
...
Final Dict: {'a': ['a', 'a', 'a'], 'c': ['c', 'c'], 'd': ['d', 'd'], 'b': ['b']}
>>> from collections import defaultdict
...
... final_defaultdict = defaultdict(list)
... for letter in letters:
... final_defaultdict[letter].append(letter)
...
... print("Final Default Dict:", final_defaultdict)
...
Final Default Dict: defaultdict(<class 'list'>, {'a': ['a', 'a', 'a'], 'c': ['c', 'c'], 'd': ['d', 'd'], 'b': ['b']})
结论
在阅读本文之前,我们可能已经了解了一些技巧,但是希望仍然对这些技巧有所了解。在项目中实践这些惯用用法将使您的Python代码更具可读性和性能。
如果本文对小伙伴有帮助,希望可以在文末来个“一键三连”。
交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~
本文分享自微信公众号 - 小白学视觉(NoobCV)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
iOS Abort问题系统性解决方案
一、背景 崩溃(Crash),即闪退,多指移动设备(如iOS、Android设备)在打开/使用应用程序的过程中,突然出现意外退出/中断的情况。如果App线上版本频繁发生崩溃,会极大地影响用户体验,甚至导致用户流失,以及收益减少。因此,崩溃问题是客户端稳定性团队需要重点解决的问题。 然而,对于所有崩溃场景,仅25%的崩溃可通过信号量捕获,实施相应改进;另有75%的崩溃则难以识别,从而对App的用户体验,造成了巨大的潜在影响。 Facebook的工程师将App退出分为以下6个类别:1.App内部主动调用exit()或abort()退出;2.App升级过程中,用户进程被杀死;3.系统升级过程中,用户进程被杀死;4.App在后台被杀死;5.App在前台被杀死,且可获取堆栈;6.App在前台被杀死,且无法获取堆栈。 对于第1~4类退出,属于App的正常退出,对用户体验没有太大影响,无需进行相应处理;对于第5类退出,可通过堆栈代码级定位崩溃原因,对此业界已形成比较成熟的解决方案,推荐免费试用阿里云的崩溃分析服务,即可快速定位、解决此类崩溃问题;对于第6类退出,可能的原因很多,包括但不限于:系统内存...
- 下一篇
从点一个灯开始学写Linux字符设备驱动
关注、星标 嵌入式客栈 ,精彩及时送达 [导读] 前一篇文章,介绍了如何将一个hello word模块编译进内核或者编译为动态加载内核模块,本篇来介绍一下如何利用Linux驱动模型来完成一个LED灯设备驱动。点一个灯有什么好谈呢?况且Linux下有专门的leds驱动子系统。 点灯有啥好聊呢? 在很多嵌入式系统里,有可能需要实现数字开关量输出,比如: LED状态显示 阀门/继电器控制 蜂鸣器 ...... 嵌入式Linux一般需求千变万化,也不可能这些需求都有现成设备驱动代码可供使用,所以如何学会完成一个开关量输出设备的驱动,一方面点个灯可以比较快了解如何具体写一个字符类设备驱动,另一方面实际项目中对于开关量输出设备就可以这样干,所以是具有较强的实用价值的。 要完成这样一个开关量输出GPIO的驱动程序,需要梳理梳理下面这些概念: 设备编号 设备挂载 关键数据结构 设备编号 字符设备是通过文件系统内的设备名称进行访问的,其本质是设备文件系统树的节点。故Linux下设备也是一个文件,Linux下字符设备在/dev目录下。可以在开发板的控制台或者编译的主Linux系统中利用ls -l /dev...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS7设置SWAP分区,小内存服务器的救世主
- CentOS7安装Docker,走上虚拟化容器引擎之路
- CentOS8安装MyCat,轻松搞定数据库的读写分离、垂直分库、水平分库
- CentOS7编译安装Gcc9.2.0,解决mysql等软件编译问题
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- CentOS7,8上快速安装Gitea,搭建Git服务器
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- SpringBoot2全家桶,快速入门学习开发网站教程
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装