用這10個(gè)小技巧加速Python編程
點(diǎn)擊上方“小白學(xué)視覺”,選擇加"星標(biāo)"或“置頂”
重磅干貨,第一時(shí)間送達(dá)

編碼很有趣,而Python編碼更有趣,因?yàn)橛泻芏嗖煌姆椒梢詫?shí)現(xiàn)相同的功能。但是,大多數(shù)時(shí)候都有一些首選的實(shí)現(xiàn)方法,有些人將其稱為Pythonic。這些Pythonic的共同特征是實(shí)現(xiàn)的代碼簡(jiǎn)潔明了。
1.負(fù)索引
人們喜歡使用序列,因?yàn)楫?dāng)我們知道元素的順序,我們就可以按順序操作這些元素。在Python中,字符串、元組和列表是最常見的序列數(shù)據(jù)類型。我們可以使用索引訪問(wèn)單個(gè)項(xiàng)目。與其他主流編程語(yǔ)言一樣,Python支持基于0的索引,在該索引中,我們?cè)谝粚?duì)方括號(hào)內(nèi)使用零訪問(wèn)第一個(gè)元素。此外,我們還可以使用切片對(duì)象來(lái)檢索序列的特定元素,如下面的代碼示例所示。
# 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通過(guò)支持負(fù)索引而進(jìn)一步走了一步。具體來(lái)說(shuō),我們可以使用-1來(lái)引用序列中的最后一個(gè)元素,并向后計(jì)數(shù)。例如,最后一個(gè)元素的索引為-2,依此類推。重要的是,負(fù)索引也可以與切片對(duì)象中的正索引一起使用。
# 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()創(chuàng)建字符串列表
# 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.三元表達(dá)
# 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.帶文件對(duì)象的語(yǔ)句
# 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.評(píng)估多個(gè)條件
# 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.在函數(shù)聲明中使用默認(rèn)值
# 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.使用計(jì)數(shù)器進(jìn)行元素計(jì)數(shù)
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']})
結(jié)論
在閱讀本文之前,我們可能已經(jīng)了解了一些技巧,但是希望仍然對(duì)這些技巧有所了解。在項(xiàng)目中實(shí)踐這些慣用用法將使您的Python代碼更具可讀性和性能。
如果本文對(duì)小伙伴有幫助,希望可以在文末來(lái)個(gè)“一鍵三連”。

交流群
歡迎加入公眾號(hào)讀者群一起和同行交流,目前有SLAM、三維視覺、傳感器、自動(dòng)駕駛、計(jì)算攝影、檢測(cè)、分割、識(shí)別、醫(yī)學(xué)影像、GAN、算法競(jìng)賽等微信群(以后會(huì)逐漸細(xì)分),請(qǐng)掃描下面微信號(hào)加群,備注:”昵稱+學(xué)校/公司+研究方向“,例如:”張三?+?上海交大?+?視覺SLAM“。請(qǐng)按照格式備注,否則不予通過(guò)。添加成功后會(huì)根據(jù)研究方向邀請(qǐng)進(jìn)入相關(guān)微信群。請(qǐng)勿在群內(nèi)發(fā)送廣告,否則會(huì)請(qǐng)出群,謝謝理解~
