用这10个小技巧加速Python编程
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 "", 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“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~
评论