新聞中心
有用的20個(gè)python代碼段(5):

成都創(chuàng)新互聯(lián)專注于企業(yè)成都營(yíng)銷網(wǎng)站建設(shè)、網(wǎng)站重做改版、阜城網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5響應(yīng)式網(wǎng)站、商城系統(tǒng)網(wǎng)站開(kāi)發(fā)、集團(tuán)公司官網(wǎng)建設(shè)、成都外貿(mào)網(wǎng)站建設(shè)公司、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為阜城等各大城市提供網(wǎng)站開(kāi)發(fā)制作服務(wù)。
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更多Python知識(shí),請(qǐng)關(guān)注:Python自學(xué)網(wǎng)!!
網(wǎng)站欄目:創(chuàng)新互聯(lián)Python教程:有用的20個(gè)python代碼段(5)
本文地址:http://fisionsoft.com.cn/article/copcgoo.html


咨詢
建站咨詢
