用这10个小技巧加速Python编程
点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达

编码很有趣,而Python编码更有趣,因为有很多不同的方法可以实现相同的功能。但是,大多数时候都有一些首选的实现方法,有些人将其称为Pythonic。这些Pythonic的共同特征是实现的代码简洁明了。
1.负索引
人们喜欢使用序列,因为当我们知道元素的顺序,我们就可以按顺序操作这些元素。在Python中,字符串、元组和列表是最常见的序列数据类型。我们可以使用索引访问单个项目。与其他主流编程语言一样,Python支持基于0的索引,在该索引中,我们在一对方括号内使用零访问第一个元素。此外,我们还可以使用切片对象来检索序列的特定元素,如下面的代码示例所示。
# Positive Indexingnumbers = [1, 2, 3, 4, 5, 6, 7, 8]print("First Number:", numbers[0])print("First Four Numbers:", numbers[:4])print("Odd Numbers:", numbers[::2])...First Number: 1First Four Numbers: [1, 2, 3, 4]Odd Numbers: [1, 3, 5, 7]
但是,Python通过支持负索引而进一步走了一步。具体来说,我们可以使用-1来引用序列中的最后一个元素,并向后计数。例如,最后一个元素的索引为-2,依此类推。重要的是,负索引也可以与切片对象中的正索引一起使用。
# Negative Indexingdata_shape = (100, 50, 4)names = ["John", "Aaron", "Mike", "Danny"]hello = "Hello World!"...print(data_shape[-1])print(names[-3:-1])print(hello[1:-1:2])...4['Aaron', 'Mike']el ol
2.检查容器是否为空
if len(some_list) > 0:# do something here when the list is not emptyelse:# 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 waycolumns = ['name', 'age', 'gender', 'address', 'account_type']print("* Literals:", columns)...# Do this insteadcolumns = 'name age gender address account_type'.split()print("* Split with spaces:", columns)...# If the strings contain spaces, you can use commas insteadcolumns = 'name, age, gender, address, account type'.split(', ')print("* Split with commas:", columns)...* 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 wayif score > 90:reward = "1000 dollars"else:reward = "500 dollars"# Do this insteadreward = "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 notreward = reward_known or "500 dollars"# The above line of code is equivalent to belowreward = 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 datatext_file0 = open("hello_world.txt", "a")text_file0.write("Hello Python!")...# Open the file again for something elsetext_file1 = open("hello_world.txt")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 wayif a < 4 and a > 1:# do something here# Do this insteadif 1 < a < 4:# do somerthing here
# The typical wayif 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 waysif a < 10 and b > 5 and c == 4:# do somethingif a < 10 or b > 5 or c == 4:# do something# Do these insteadif 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 imagegenerate_plot(data, None)# The one with a default valuedef generate_plot(data, image_name=None):pass# Now, we can omit the second parametergenerate_plot(data)
8.使用计数器进行元素计数
words = ['an', 'boy', 'girl', 'an', 'boy', 'dog', 'cat', 'Dog', 'CAT', 'an','GIRL', 'AN', 'dog', 'cat', 'cat', 'bag', 'BAG', 'BOY', 'boy', 'an']unique_words = {x.lower() for x in set(words)}for word in unique_words:print(f"* Count of {word}: {words.count(word)}")...* 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...word_counter = Counter(x.lower() for x in words)print("Word Counts:", word_counter)...Word Counts: Counter({'an': 5, 'boy': 4, 'cat': 4, 'dog': 3, 'girl': 2, 'bag': 2})
# Find out the most common itemprint("Most Frequent:", word_counter.most_common(1))Most Frequent: [('an', 5)]# Find out the most common 2 itemsprint("Most Frequent:", word_counter.most_common(2))Most Frequent: [('an', 5), ('boy', 4)]
9.按不同的订单要求排序
# A list of numbers and stringsnumbers = [1, 3, 7, 2, 5, 4]words = ['yay', 'bill', 'zen', 'del']# Sort themprint(sorted(numbers))print(sorted(words))...[1, 2, 3, 4, 5, 7]['bill', 'del', 'yay', 'zen']# Sort them in descending orderprint(sorted(numbers, reverse=True))print(sorted(words, reverse=True))...[7, 5, 4, 3, 2, 1]['zen', 'yay', 'del', 'bill']
# Create a list of tuplesgrades = [('John', 95), ('Aaron', 99), ('Zack', 97), ('Don', 92), ('Jennifer', 100), ('Abby', 94), ('Zoe', 99), ('Dee', 93)]# Sort by the grades, descendingsorted(grades, key=lambda x: x[1], reverse=True)[('Jennifer', 100), ('Aaron', 99), ('Zoe', 99), ('Zack', 97), ('John', 95), ('Abby', 94), ('Dee', 93), ('Don', 92)]# Sort by the name's initial letter, ascendingsorted(grades, key=lambda x: x[0][0])[('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 worksorted(grades, key=lambda x: (x[0][0], x[1]), reverse=True)[('Zoe', 99), ('Zack', 97), ('Jennifer', 100), ('John', 95), ('Dee', 93), ('Don', 92), ('Aaron', 99), ('Abby', 94)]sorted(grades, key=lambda x: (x[0][0], x[1]), reverse=False)[('Abby', 94), ('Aaron', 99), ('Don', 92), ('Dee', 93), ('John', 95), ('Jennifer', 100), ('Zack', 97), ('Zoe', 99)]# This will do the tricksorted(grades, key=lambda x: (x[0][0], -x[1]))[('Aaron', 99), ('Abby', 94), ('Dee', 93), ('Don', 92), ('Jennifer', 100), ('John', 95), ('Zoe', 99), ('Zack', 97)]
10.不要忘记defaultdict
> student = {'name': "John", 'age': 18}... student['gender']...Traceback (most recent call last):File "", line 2, in <module>KeyError: 'gender'
letters = ["a", "a", "c", "d", "d", "c", "a", "b"]final_dict = {}for letter in letters:if letter not in final_dict:final_dict[letter] = []final_dict[letter].append(letter)...print("Final Dict:", final_dict)...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“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~
评论
