創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!
本篇文章為大家展示了python的實(shí)際應(yīng)用案例,代碼簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
1、列表清單扁平化
有時(shí)你不確定列表的嵌套深度,而且只想全部要素在單個(gè)平面列表中。
可以通過(guò)以下方式獲得:
from iteration_utilities import deepflatten # if you only have one depth nested_list, use this def flatten(l): return [item for sublist in l for item in sublist] l = [[1,2,3],[3]] print(flatten(l)) # [1, 2, 3, 3] # if you don't know how deep the list is nested l = [[1,2,3],[4,[5],[6,7]],[8,[9,[10]]]] print(list(deepflatten(l, depth=3))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
若有正確格式化的數(shù)組,Numpy扁平化是更佳選擇。
2、列表取樣
通過(guò)使用random軟件庫(kù),以下代碼從給定的列表中生成了n個(gè)隨機(jī)樣本。
import random my_list = ['a', 'b', 'c', 'd', 'e'] num_samples = 2 samples = random.sample(my_list,num_samples) print(samples) # [ 'a', 'e'] this will have any 2 random values
強(qiáng)烈推薦使用secrets軟件庫(kù)生成用于加密的隨機(jī)樣本。
以下代碼僅限用于Python 3。
import secrets # imports secure module. secure_random = secrets.SystemRandom() # creates a secure random object. my_list = ['a','b','c','d','e'] num_samples = 2 samples = secure_random.sample(my_list, num_samples) print(samples) # [ 'e', 'd'] this will have any 2 random values
3、數(shù)字化
以下代碼將一個(gè)整數(shù)轉(zhuǎn)換為數(shù)字列表。
num = 123456 # using map list_of_digits = list(map(int, str(num))) print(list_of_digits) # [1, 2, 3, 4, 5, 6] # using list comprehension list_of_digits = [int(x) for x in str(num)] print(list_of_digits) # [1, 2, 3, 4, 5, 6]
4、檢查唯一性
以下函數(shù)將檢查一個(gè)列表中的所有要素是否唯一。
def unique(l): if len(l)==len(set(l)): print("All elements are unique") else: print("List has duplicates") unique([1,2,3,4]) # All elements are unique unique([1,1,2,3]) # List has duplicates
上述內(nèi)容就是python的實(shí)際應(yīng)用案例,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道。
當(dāng)前文章:python的實(shí)際應(yīng)用案例-創(chuàng)新互聯(lián)
本文地址:http://www.hntjjpw.com/article9/gisoh.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、關(guān)鍵詞優(yōu)化、動(dòng)態(tài)網(wǎng)站、靜態(tài)網(wǎng)站、企業(yè)建站、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容