15個短代碼示例理解python豐富的編程思維
1.檢查重復(fù)元素
下面的方法可以檢查給定列表中是否有重復(fù)的元素。它使用了 set() 屬性,該屬性將會從列表中刪除重復(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.變位詞
檢測兩個字符串是否互為變位詞(即互相顛倒字符順序)
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é)大小計算
以下方法將以字節(jié)為單位返回字符串長度。
def byte_size(string): return(len(string.encode( utf-8 ))) byte_size( ???? ) # 4 byte_size( Hello World ) # 11
5.重復(fù)打印字符串 N 次
以下代碼不需要使用循環(huán)即可打印某個字符串 n 次
n = 2 s ="Programming" print(s * n); # ProgrammingProgramming
6.首字母大寫
以下代碼段使用 title() 方法將字符串內(nèi)的每個詞進(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() 刪除列表中的錯誤值(如: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)換一個二維數(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
11.逗號分隔
以下代碼段可將字符串列表轉(zhuǎn)換為單個字符串,列表中的每個元素用逗號分隔。
hobbies = ["basketball", "football", "swimming"] print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
12.計算元音字母數(shù)
以下方法可計算字符串中元音字母(‘a(chǎn)', ‘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.首字母恢復(fù)小寫
以下方法可用于將給定字符串的第一個字母轉(zhuǎn)換為小寫。
def decapitalize(string): return str[:1].lower() + str[1:] decapitalize( FooBar ) # fooBar decapitalize( FooBar ) # fooBar
14.平面化
以下方法使用遞歸來展開潛在的深度列表。
def spread(arg): ret = [] for i in arg: if isinstance(i, list): ret.extend(i) else: ret.append(i) return retdef 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.差異
該方法只保留第一個迭代器中的值,從而發(fā)現(xiàn)兩個迭代器之間的差異。
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]
以上就是15個短代碼示例理解python豐富的編程思維的詳細(xì)內(nèi)容,更多關(guān)于python短代碼編程思維的資料請關(guān)注本站其它相關(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處理。