15個(gè)短代碼示例理解python豐富的編程思維
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
11.逗號分隔
以下代碼段可將字符串列表轉(zhuǎn)換為單個(gè)字符串,列表中的每個(gè)元素用逗號分隔。
hobbies = ["basketball", "football", "swimming"] print("My hobbies are: " + ", ".join(hobbies)) # My hobbies are: basketball, football, swimming
12.計(jì)算元音字母數(shù)
以下方法可計(jì)算字符串中元音字母(‘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ù)小寫
以下方法可用于將給定字符串的第一個(gè)字母轉(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.差異
該方法只保留第一個(gè)迭代器中的值,從而發(fā)現(xiàn)兩個(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]
以上就是15個(gè)短代碼示例理解python豐富的編程思維的詳細(xì)內(nèi)容,更多關(guān)于python短代碼編程思維的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
對PyTorch torch.stack的實(shí)例講解
今天小編就為大家分享一篇對PyTorch torch.stack的實(shí)例講解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07使用Python實(shí)現(xiàn)將多表分批次從數(shù)據(jù)庫導(dǎo)出到Excel
這篇文章主要介紹了使用Python實(shí)現(xiàn)將多表分批次從數(shù)據(jù)庫導(dǎo)出到Excel,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05python?pandas分割DataFrame中的字符串及元組的方法實(shí)現(xiàn)
本文主要介紹了python?pandas分割DataFrame中的字符串及元組的方法實(shí)現(xiàn),主要介紹了3種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2022-03-03Python實(shí)現(xiàn)圖像壓縮和圖像處理詳解
隨著現(xiàn)在短視頻類越來越火,隨之而來的就是大量的視頻圖像的處理。這篇文章主要為大家介紹了Python如何一鍵實(shí)現(xiàn)圖像壓縮和圖像處理,希望對你們有所幫助2022-07-07