這種流行的部分原因是它的簡單性和易于學(xué)習(xí)。
在本文中涮毫,我將向大家介紹 30 個簡短瞬欧、實用的 Python 技巧。 內(nèi)容較多罢防,建議收藏學(xué)習(xí)艘虎,喜歡點贊關(guān)注支持。
1. All unique
下面的方法檢查給定的列表是否有重復(fù)的元素咒吐,它使用 set() 的屬性從列表中刪除重復(fù)的元素野建。
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True</pre>
此方法可用于檢查兩個字符串是否為字謎。 字謎是通過重新排列不同單詞或短語的字母而形成的單詞或短語恬叹,通常只使用一次所有原始字母候生。
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True</pre>
3. 內(nèi)存
此代碼段可用于檢查對象的內(nèi)存使用情況。
variable = 30
print(sys.getsizeof(variable)) # 24</pre>
4. Byte 大小
此方法以 Byte 為單位返回字符串的長度绽昼。
return(len(string.encode('utf-8')))
byte_size('?') # 4
byte_size('Hello World') # 11 </pre>
5. 打印一個字符串 N 次
此代碼段可用于打印字符串 n 次唯鸭,而無需使用循環(huán)來執(zhí)行此操作。
s ="Programming"
print(s * n) # ProgrammingProgramming</pre>
6. 首字母大寫
此代碼段僅使用 title() 方法將字符串中每個單詞的首字母大寫硅确。
<pre class="prettyprint hljs lisp" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">s = "programming is awesome"
print(s.title()) # Programming Is Awesome</pre>
7.列表切割
此方法將列表分為指定大小的較小列表目溉。
return [list[i:i+size] for i in range(0,len(list), size)]</pre>
8. 刪除虛假值
此方法使用 filter() 從列表中刪除虛假值(False、None菱农、0 和“”)
return list(filter(None, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]</pre>
9. 轉(zhuǎn)置二維數(shù)組
此代碼段可用于轉(zhuǎn)置二維數(shù)組
transposed = zip(*array)
print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]</pre>
10. 鏈?zhǔn)奖容^
您可以在一行中對各種運算符進(jìn)行多次比較缭付。
print( 2 < a < 8) # True
print(1 == a < 2) # False</pre>
11.逗號分隔
此代碼段可用于將字符串列表轉(zhuǎn)換為單個字符串,列表中的每個元素用逗號分隔循未。
print("My hobbies are:") # My hobbies are:
print(", ".join(hobbies)) # basketball, football, swimming</pre>
12.獲取元音
此方法獲取字符串中的元音(‘a(chǎn)’陷猫、‘e’、‘i’、‘o’绣檬、‘u’)
return [each for each in string if each in 'aeiou']
get_vowels('foobar') # ['o', 'o', 'a']
get_vowels('gym') # []</pre>
13. 轉(zhuǎn)化
此方法可用于將給定字符串的第一個字母轉(zhuǎn)換為小寫舅巷。
return str[:1].lower() + str[1:]
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'</pre>
14. 壓平
以下方法使用遞歸來展平潛在的深層列表下硕。
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(xs):
flat_list = []
[flat_list.extend(deep_flatten(x)) for x in xs] if isinstance(xs, list) else flat_list.append(xs)
return flat_list
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]</pre>
15. 差異
此方法通過僅保留第一個中的值來查找兩個迭代之間的差異蜜葱。
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
difference([1,2,3], [1,2,4]) # [3]</pre>
16. 差異化
在將給定函數(shù)應(yīng)用于兩個列表的每個元素后,以下方法返回兩個列表之間的差異掘譬。
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]
difference_by([{
'x': 2 }, {
'x': 1 }], [{
'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]</pre>
17. 鏈?zhǔn)胶瘮?shù)調(diào)用
您可以在一行中調(diào)用多個函數(shù)
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9 </pre>
18.重復(fù)值
以下方法通過使用 set() 僅包含唯一元素這一事實忘蟹,來檢查列表是否具有重復(fù)值飒房。
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False</pre>
19. 合并兩個字典
以下方法可用于合并兩個字典
c = a.copy() # make a copy of a
c.update(b) # modify keys and values of a with the ones from b
return c
a = {
'x': 1, 'y': 2}
b = {
'y': 3, 'z': 4}
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}</pre>
在 Python 3.5 及更高版本中,您還可以像下面這樣:
return { **a, **b}
a = {
'x': 1, 'y': 2}
b = {
'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}</pre>
20. 將兩個列表轉(zhuǎn)換成字典
以下方法可用于將兩個列表轉(zhuǎn)換為字典
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}</pre>
21.使用枚舉
此代碼段顯示您可以使用 enumerate 來獲取列表的值和索引媚值。
for index, element in enumerate(list):
print("Value", element, "Index ", index, )
# ('Value', 'a', 'Index ', 0)
# ('Value', 'b', 'Index ', 1)
#('Value', 'c', 'Index ', 2)
# ('Value', 'd', 'Index ', 3) </pre>
22. 計算花費的時間
此代碼段可用于計算執(zhí)行特定代碼所需的時間狠毯。
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) #3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)
# ('Time: ', 1.1205673217773438e-05)</pre>
23. try/else
您可以將 else 子句作為 try/except 塊的一部分,如果沒有拋出異常褥芒,就會執(zhí)行該塊嚼松。
2*3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
#Thank God, no exceptions were raised.</pre>
24. 統(tǒng)計最頻繁
此方法返回列表中出現(xiàn)頻率最高的元素。
return max(set(list), key = list.count)
numbers = [1,2,1,2,3,2,1,4,2]
most_frequent(numbers)</pre>
25. 回文
此方法檢查給定字符串是否為回文锰扶。
return a == a[::-1]
palindrome('mom') # True</pre>
26. 沒有 if-else 的計算器
下面的代碼片段展示了如何在不需要使用 if-else 條件的情況下編寫一個簡單的計算器献酗。
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25</pre>
27.shuffle
此代碼段可用于隨機(jī)化列表中元素的順序。 請注意坷牛,shuffle 就地工作罕偎,并返回 None。
foo = [1, 2, 3, 4]
shuffle(foo)
print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]</pre>
28. 列表展平
此方法類似于 JavaScript 中的 [].concat(…arr) 將列表展平京闰。
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]</pre>
29. 交換值
這是交換兩個變量而無需使用額外變量的一種非逞占埃快速的方法。
a, b = b, a
print(a) # 14
print(b) # -1</pre>
30. 獲取缺失鍵的默認(rèn)值
此代碼段顯示了在字典中未包含您要查找的鍵的情況下如何獲取默認(rèn)值蹂楣。
print(d.get('c', 3)) # 3</pre>
技術(shù)交流
歡迎轉(zhuǎn)載俏站、收藏、有所收獲點贊支持一下痊土!