喝杯咖啡的功夫就能學(xué)會的100個非常有用的Python技巧(3)
點(diǎn)擊上方“程序員大白”,選擇“星標(biāo)”公眾號
重磅干貨,第一時間送達(dá)
作者:Fatos Morina
編譯:ronghuaiyang
接上一篇,67~100條。
67. 根據(jù)參數(shù)從右側(cè)移除字符
string = "This is a sentence with "
# Remove trailing spaces from the right
print(string.rstrip()) # "This is a sentence with"
string = "this here is a sentence…..,,,,aaaaasd"
print(string.rstrip(“.,dsa”)) # "this here is a sentence"
類似地,你可以根據(jù)參數(shù)從左邊刪除字符:
string = "ffffffffFirst"
print(string.lstrip(“f”)) # First
68. 檢查一個字符串是否代表一個數(shù)字
string = "seven"
print(string.isdigit()) # Falsestring = "1337"
print(string.isdigit()) # Truestring = "5a"
print(string.isdigit()) # False, because it contains the character 'a'string = "2**5"
print(string.isdigit()) # False
69. 檢查一個字符串是否代表一個中文數(shù)字
# 42673 in Arabic numerals
string = "四二六七三"
print(string.isdigit()) # False
print(string.isnumeric()) # True
70. 檢查一個字符串是否所有的單詞都以大寫字母開頭
string = "This is a sentence"
print(string.istitle()) # False
string = "10 Python Tips"
print(string.istitle()) # True
string = "How to Print A String in Python"
# False, because of the first characters being lowercase in "to" and "in"
print(string.istitle())
string = "PYTHON"
print(string.istitle()) # False. It's titlelized version is "Python"
71. 我們也可以在元組中使用負(fù)索引
numbers = (1, 2, 3, 4)
print(numbers[-1]) # 4
print(numbers[-4]) # 1
72. 在元組中嵌套列表和元組
mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third'])
print(mixed_tuple[1]) # ['first', 'second', 'third']
print(mixed_tuple[0]) # ('aaaaaaaaaa', 3, 4)
73. 快速計算滿足條件的元素在列表中出現(xiàn)的次數(shù)
names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"]
print(names.count("Besim")) # 2
74. 使用slice()可以方便的得到最近的元素
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slicing = slice(-4, None)
# Getting the last 3 elements from the list
print(my_list[slicing]) # [4, 5, 6]
# Getting only the third element starting from the right
print(my_list[-3]) # 4
你也可以使用*slice()*來完成其他常見的切片任務(wù),比如:
string = "Data Science"
# start = 1, stop = None (don't stop anywhere), step = 1
# contains 1, 3 and 5 indices
slice_object = slice(5, None)
print(string[slice_object]) # Science
75. 計算元素在元組中出現(xiàn)的次數(shù)
my_tuple = ('a', 1, 'f', 'a', 5, 'a')
print(my_tuple.count('a')) # 3
76. 獲取元組中元素的索引
my_tuple = ('a', 1, 'f', 'a', 5, 'a')
print(my_tuple.index('f')) # 2
77. 通過跳轉(zhuǎn)獲取子元組
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(my_tuple[::3]) # (1, 4, 7, 10)
78. 從索引開始獲取子元組
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(my_tuple[3:]) # (4, 5, 6, 7, 8, 9, 10)
79. 從列表、集合或字典中刪除所有元素
my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list) # []
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # set()
my_dict = {"a": 1, "b": 2}
my_dict.clear()
print(my_dict) # {}
80. 合并2個集合
一種方法是使用方法union(),它將作為合并的結(jié)果返回一個新的集合:
first_set = {4, 5, 6}
second_set = {1, 2, 3}
print(first_set.union(second_set)) # {1, 2, 3, 4, 5, 6}
另一個是方法update,它將第二個集合的元素插入到第一個集合中:
first_set = {4, 5, 6}
second_set = {1, 2, 3}
first_set.update(second_set)
print(first_set) # {1, 2, 3, 4, 5, 6}
81. 打印函數(shù)內(nèi)的條件語句
def is_positive(number):
print("Positive" if number > 0 else "Negative") # Positive
is_positive(-3)
82. 一個if語句中包含多個條件
math_points = 51
biology_points = 78
physics_points = 56
history_points = 72
my_conditions = [math_points > 50, biology_points > 50,
physics_points > 50, history_points > 50]
if all(my_conditions):
print("Congratulations! You have passed all of the exams.")
else:
print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.
83. 在一個if語句中至少滿足一個條件
math_points = 51
biology_points = 78
physics_points = 56
history_points = 72
my_conditions = [math_points > 50, biology_points > 50,
physics_points > 50, history_points > 50]
if any(my_conditions):
print("Congratulations! You have passed all of the exams.")
else:
print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.
84. 任何非空字符串都被計算為True
print(bool("Non empty")) # True
print(bool("")) # False
85. 任何非空列表、元組或字典都被求值為True
print(bool([])) # False
print(bool(set([]))) # False
print(bool({})) # False
print(bool({"a": 1})) # True
86. 其他計算為False的值是None、“False”和數(shù)字0
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False
87. 你不能僅僅通過在函數(shù)中提及全局變量來改變它的值
string = "string"
def do_nothing():
string = "inside a method"
do_nothing()
print(string) # string
你也需要使用訪問修飾符global:
string = "string"
def do_nothing():
global string
string = "inside a method"
do_nothing()
print(string) # inside a method
88. 使用“collections”中的Counter計算字符串或列表中的元素數(shù)量
from collections import Counter
result = Counter("Banana")
print(result) # Counter({'a': 3, 'n': 2, 'B': 1})
result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6])
print(result) # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})
89. 使用Counter檢查是否2個字符串包含相同的字符
from collections import Counter
def check_if_anagram(first_string, second_string):
first_string = first_string.lower()
second_string = second_string.lower()
return Counter(first_string) == Counter(second_string)
print(check_if_anagram('testinG', 'Testing')) # True
print(check_if_anagram('Here', 'Rehe')) # True
print(check_if_anagram('Know', 'Now')) # False
你也可以使用*sorted()*檢查兩個字符串是否具有相同的字符:
def check_if_anagram(first_word, second_word):
first_word = first_word.lower()
second_word = second_word.lower()
return sorted(first_word) == sorted(second_word)
print(check_if_anagram("testinG", "Testing")) # True
print(check_if_anagram("Here", "Rehe")) # True
print(check_if_anagram("Know", "Now")) # False
90. 使用" itertools "中的" Count "計算元素的數(shù)量
from itertools import count
my_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
current_counter = count()
string = "This is just a sentence."
for i in string:
if i in my_vowels:
print(f"Current vowel: {i}")
print(f"Number of vowels found so far: {next(current_counter)}")
這是控制臺中的結(jié)果:
Current vowel: i
Number of vowels found so far: 0
Current vowel: i
Number of vowels found so far: 1
Current vowel: u
Number of vowels found so far: 2
Current vowel: a
Number of vowels found so far: 3
Current vowel: e
Number of vowels found so far: 4
Current vowel: e
Number of vowels found so far: 5
Current vowel: e
Number of vowels found so far: 6
91. 根據(jù)字符串或列表的頻率對元素進(jìn)行排序
來自collections模塊的Counter默認(rèn)情況下不會根據(jù)元素的頻率來排序。
from collections import Counter
result = Counter([1, 2, 3, 2, 2, 2, 2])
print(result) # Counter({2: 5, 1: 1, 3: 1})
print(result.most_common()) # [(2, 5), (1, 1), (3, 1)]
92. 在一行中找到列表中出現(xiàn)頻次最高的元素
my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']
print(max(set(my_list), key=my_list.count)) # a
93. copy()和deepcopy()的區(qū)別
來自文檔中的解釋:
淺拷貝構(gòu)造一個新的復(fù)合對象,然后(在可能的范圍內(nèi))在其中插入對原始對象的引用。深拷貝構(gòu)造一個新的復(fù)合對象,然后遞歸地將在原始對象中找到的對象的副本插入其中。
更全面的描述:
淺拷貝意味著構(gòu)造一個新的集合對象,然后用對原始集合中的子對象的引用填充它。從本質(zhì)上說,淺拷貝的深度只有一層。拷貝過程不會遞歸,因此不會創(chuàng)建子對象本身的副本。深拷貝使拷貝過程遞歸。這意味著首先構(gòu)造一個新的集合對象,然后用在原始集合對象中找到的子對象的副本遞歸地填充它。以這種方式拷貝對象將遍歷整個對象樹,以創(chuàng)建原始對象及其所有子對象的完全獨(dú)立的克隆。
這里是copy()的例子:
first_list = [[1, 2, 3], ['a', 'b', 'c']]
second_list = first_list.copy()
first_list[0][2] = 831
print(first_list) # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list) # [[1, 2, 831], ['a', 'b', 'c']]
這個是deepcopy() 的例子:
import copy
first_list = [[1, 2, 3], ['a', 'b', 'c']]
second_list = copy.deepcopy(first_list)
first_list[0][2] = 831
print(first_list) # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list) # [[1, 2, 3], ['a', 'b', 'c']]
94. 當(dāng)試圖訪問字典中不存在的鍵時,可以避免拋出錯誤
如果你使用一個普通的字典,并試圖訪問一個不存在的鍵,那么你將得到一個錯誤:
my_dictonary = {"name": "Name", "surname": "Surname"}print(my_dictonary["age"])
下面是拋出的錯誤:
KeyError: 'age'
我們可以使用defaultdict():來避免這種錯誤
from collections import defaultdict
my_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"
print(my_dictonary["age"])
95. 你可以構(gòu)建自己的迭代器
class OddNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 2
return x
odd_numbers_object = OddNumbers()
iterator = iter(odd_numbers_object)
print(next(iterator)) # 1
print(next(iterator)) # 3
print(next(iterator)) # 5
96. 可以用一行從列表中刪除重復(fù)項
my_set = set([1, 2, 1, 2, 3, 4, 5])
print(list(my_set)) # [1, 2, 3, 4, 5]
97. 打印模塊所在的位置
import torch
print(torch) # <module 'torch' from '/Users/...'
98. 可以使用" not in "來檢查值是否不屬于列表
odd_numbers = [1, 3, 5, 7, 9]
even_numbers = []
for i in range(9):
if i not in odd_numbers:
even_numbers.append(i)
print(even_numbers) # [0, 2, 4, 6, 8]
99. sort() 和 sorted()的差別
sort()對原始列表進(jìn)行排序。
sorted()返回一個新的排序列表。
groceries = ['milk', 'bread', 'tea']
new_groceries = sorted(groceries)
# new_groceries = ['bread', 'milk', 'tea']
print(new_groceries)
# groceries = ['milk', 'bread', 'tea']
print(groceries)
groceries.sort()
# groceries = ['bread', 'milk', 'tea']
print(groceries)
100. 使用uuid模塊生成唯一的id
UUID代表統(tǒng)一唯一標(biāo)識符。
import uuid
# Generate a UUID from a host ID, sequence number, and the current time
print(uuid.uuid1()) # 308490b6-afe4-11eb-95f7-0c4de9a0c5af
# Generate a random UUID
print(uuid.uuid4()) # 93bc700b-253e-4081-a358-24b60591076a

英文原文:https://towardsdatascience.com/100-helpful-python-tips-you-can-learn-before-finishing-your-morning-coffee-eb9c39e68958
推薦閱讀
國產(chǎn)小眾瀏覽器因屏蔽視頻廣告,被索賠100萬(后續(xù))
年輕人“不講武德”:因看黃片上癮,把網(wǎng)站和786名女主播起訴了
關(guān)于程序員大白
程序員大白是一群哈工大,東北大學(xué),西湖大學(xué)和上海交通大學(xué)的碩士博士運(yùn)營維護(hù)的號,大家樂于分享高質(zhì)量文章,喜歡總結(jié)知識,歡迎關(guān)注[程序員大白],大家一起學(xué)習(xí)進(jìn)步!


