超實(shí)用的 10 段 Python 案例
在本文中,我們將會(huì)介紹 30 個(gè)簡短的代碼片段,你可以在 30 秒或更短的時(shí)間里理解和學(xué)習(xí)這些代碼片段。
1.檢查重復(fù)元素
下面的方法可以檢查給定列表中是否有重復(fù)的元素。它使用了 set()
屬性,該屬性將會(huì)從列表中刪除重復(fù)的元素。
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)存使用情況
以下代碼段可用來檢查對象的內(nèi)存使用情況。
import sys variable = 30 print(sys.getsizeof(variable)) # 24
4.字節(jié)大小計(jì)算
以下方法將以字節(jié)為單位返回字符串長度。
def byte_size(string): return(len(string.encode('utf-8'))) byte_size(' ') # 4 byte_size('Hello World') # 11
5.重復(fù)打印字符串 N 次
以下代碼不需要使用循環(huán)即可打印某個(gè)字符串 n 次
n = 2; s ="Programming"; print(s * n); # ProgrammingProgramming
6.首字母大寫
以下代碼段使用 title()
方法將字符串內(nèi)的每個(gè)詞進(jìn)行首字母大寫。
s = "programming is awesome" print(s.title()) # Programming Is Awesome
7.分塊
以下方法使用 range()
將列表分塊為指定大小的較小列表。
from math import ceil def chunk(lst, size): return list( map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size))))) chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
8.壓縮
以下方法使用 fliter()
刪除列表中的錯(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.間隔數(shù)
以下代碼段可以用來轉(zhuǎn)換一個(gè)二維數(shù)組。
array = [['a', 'b'], ['c', 'd'], ['e', 'f']] transposed = zip(*array) print(transposed) # [('a', 'c', 'e'), ('b', 'd', 'f')]
10.鏈?zhǔn)奖容^
以下代碼可以在一行中用各種操作符進(jìn)行多次比較。
a = 3 print( 2 < a < 8) # True print(1 == a < 2) # False
到此這篇關(guān)于超實(shí)用的 10 段 Python 案例的文章就介紹到這了,更多相關(guān)Python 案例內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。