30秒學(xué)會(huì)30個(gè)超實(shí)用Python代碼片段【收藏版】
許多人在數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)、web開(kāi)發(fā)、腳本編寫(xiě)和自動(dòng)化等領(lǐng)域中都會(huì)使用Python,它是一種十分流行的語(yǔ)言。
Python流行的部分原因在于簡(jiǎn)單易學(xué)。
本文將簡(jiǎn)要介紹30個(gè)簡(jiǎn)短的、且能在30秒內(nèi)掌握的代碼片段。
1. 唯一性
以下方法可以檢查給定列表是否有重復(fù)的地方,可用set()的屬性將其從列表中刪除。
def all_unique(lst): 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
2. 變位詞(相同字母異序詞)
此方法可用于檢查兩個(gè)字符串是否為變位詞。
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
3. 內(nèi)存
此代碼段可用于檢查對(duì)象的內(nèi)存使用情況。
import sys variable = 30 print(sys.getsizeof(variable)) # 24
4. 字節(jié)大小
此方法可輸出字符串的字節(jié)大小。
def byte_size(string):
return(len(string.encode('utf-8')))
byte_size('😀') # 4
byte_size('Hello World') # 11
5. 打印N次字符串
此代碼段無(wú)需經(jīng)過(guò)循環(huán)操作便可多次打印字符串。
n = 2; s ="Programming"; print(s * n); # ProgrammingProgramming
6. 首字母大寫(xiě)
以下代碼片段只利用了title(),就能將字符串中每個(gè)單詞的首字母大寫(xiě)。
s = "programming is awesome" print(s.title()) # Programming Is Awesome
7. 列表細(xì)分
該方法將列表細(xì)分為特定大小的列表。
def chunk(list, size): return [list[i:i+size] for i in range(0,len(list), size)]
8. 壓縮
以下代碼使用filter()從,將錯(cuò)誤值(False、None、0和“ ”)從列表中刪除。
def compact(lst): return list(filter(bool, lst)) compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]
9. 計(jì)數(shù)
以下代碼可用于調(diào)換2D數(shù)組排列。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
10. 鏈?zhǔn)奖容^
以下代碼可對(duì)各種運(yùn)算符進(jìn)行多次比較。
a = 3 print( 2 < a < 8) # True print(1 == a < 2) # False
11. 逗號(hào)分隔
此代碼段可將字符串列表轉(zhuǎn)換為單個(gè)字符串,同時(shí)將列表中的每個(gè)元素用逗號(hào)隔開(kāi)。
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
12. 元音計(jì)數(shù)
此方法可計(jì)算字符串中元音(“a”、“e”、“i”、“o”、“u”)的數(shù)目。
import re
def count_vowels(str):
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE))
count_vowels('foobar') # 3
count_vowels('gym') # 0
13. 首字母小寫(xiě)
此方法可將給定字符串的首字母轉(zhuǎn)換為小寫(xiě)模式。
def decapitalize(string):
return str[:1].lower() + str[1:]
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'
14. 展開(kāi)列表
下列代碼采用了遞歸法展開(kāi)潛在的深層列表。
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
15. 尋找差異
此方法僅保留第一個(gè)迭代中的值來(lái)查找兩個(gè)迭代之間的差異
def difference(a, b): 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]
16. 輸出差異
以下方法利用已有函數(shù),尋找并輸出兩個(gè)列表之間的差異。
def difference_by(a, b, fn):
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 } ]
17. 鏈?zhǔn)胶瘮?shù)調(diào)用
以下方法可以實(shí)現(xiàn)在一行中調(diào)用多個(gè)函數(shù)
def add(a, b): return a + b def subtract(a, b): return a – b a, b = 4, 5 print((subtract if a > b else add)(a, b)) # 9
18. 重復(fù)值存在與否
以下方法利用set()只包含唯一元素的特性來(lái)檢查列表是否存在重復(fù)值。
def has_duplicates(lst): 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
19. 合并字庫(kù)
以下方法可將兩個(gè)字庫(kù)合并。
def merge_two_dicts(a, b):
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}
在Python3.5及升級(jí)版中,也可按下列方式執(zhí)行步驟代碼:
def merge_dictionaries(a, b)
return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
20. 將兩個(gè)列表轉(zhuǎn)換為字庫(kù)
以下方法可將兩個(gè)列表轉(zhuǎn)換為字庫(kù)。
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}
21. 列舉
以下代碼段可以采用列舉的方式來(lái)獲取列表的值和索引。
list = ["a", "b", "c", "d"]
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)
22. 時(shí)間成本
以下代碼可計(jì)算執(zhí)行特定代碼所需的時(shí)間。
import time
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)
23. Try else語(yǔ)句
可將else句作為try/except語(yǔ)句的一部分,如果沒(méi)有異常情況,則執(zhí)行else語(yǔ)句。
try:
2*3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
#Thank God, no exceptions were raised.
24. 出現(xiàn)頻率最高的元素
此方法將輸出列表中出鏡率最高的元素。
def most_frequent(list): return max(set(list), key = list.count) list = [1,2,1,2,3,2,1,4,2] most_frequent(list)
25. 回文(正反讀有一樣的字符串)
以下代碼檢查給定字符串是否為回文。首先將字符串轉(zhuǎn)換為小寫(xiě),然后從中刪除非字母字符,最后將新字符串版本與原版本進(jìn)行比對(duì)。
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
palindrome('taco cat') # True
26. 不用if-else語(yǔ)句的計(jì)算器
以下代碼片段展示了如何在不用if-else條件語(yǔ)句的情況下,編寫(xiě)簡(jiǎn)易計(jì)算器。
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25
27. 隨機(jī)排序
該算法采用Fisher-Yates algorithm對(duì)新列表中的元素進(jìn)行隨機(jī)排序。
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
28. 展開(kāi)列表
此方法將類似javascript中[].concat(…arr)這樣的列表展開(kāi)。
def spread(arg):
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]
29. 交換變量
此方法為能在不使用額外變量的情況下快速交換兩種變量。
def swap(a, b): return b, a a, b = -1, 14 swap(a, b) # (14, -1)
30. 獲取丟失部分的默認(rèn)值
以下代碼可在所需對(duì)象不在字庫(kù)范圍內(nèi)的情況下獲取默認(rèn)值。
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3
本文只簡(jiǎn)單介紹了一些能在日常工作中幫到我們的方法。但內(nèi)容都主要立足于GitHub 存儲(chǔ)庫(kù):https://github.com/30-seconds/30_seconds_of_knowledge,該存儲(chǔ)庫(kù)還包含了有關(guān)Python及其他語(yǔ)言和技術(shù)行之有效的代碼。
相關(guān)文章
Python imageio讀取視頻并進(jìn)行編解碼詳解
今天小編就為大家分享一篇Python imageio讀取視頻并進(jìn)行編解碼詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
python里讀寫(xiě)excel等數(shù)據(jù)文件的6種常用方式(小結(jié))
這篇文章主要介紹了python里讀寫(xiě)excel等數(shù)據(jù)文件的6種常用方式(小結(jié)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
django如何根據(jù)現(xiàn)有數(shù)據(jù)庫(kù)表生成model詳解
這篇文章主要給大家介紹了關(guān)于django如何根據(jù)現(xiàn)有數(shù)據(jù)庫(kù)表生成model的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Django具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-08-08
python學(xué)習(xí)之使用Matplotlib畫(huà)實(shí)時(shí)的動(dòng)態(tài)折線圖的示例代碼
這篇文章主要介紹了python學(xué)習(xí)之使用Matplotlib畫(huà)實(shí)時(shí)的動(dòng)態(tài)折線圖的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
Windows和夜神模擬器上抓包程序mitmproxy的安裝使用詳解
mitmproxy是一個(gè)支持HTTP和HTTPS的抓包程序,有類似Fiddler、Charles的功能,只不過(guò)它是一個(gè)控制臺(tái)的形式操作,這篇文章主要介紹了Windows和夜神模擬器上抓包程序mitmproxy的安裝使用詳解,需要的朋友可以參考下2022-10-10
使用Tensorflow實(shí)現(xiàn)可視化中間層和卷積層
今天小編就為大家分享一篇使用Tensorflow實(shí)現(xiàn)可視化中間層和卷積層,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01

