日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網營銷解決方案
創(chuàng)新互聯(lián)Python教程:有用的20個python代碼段(5)

有用的20個python代碼段(5):

成都創(chuàng)新互聯(lián)專注于企業(yè)成都營銷網站建設、網站重做改版、阜城網站定制設計、自適應品牌網站建設、H5響應式網站商城系統(tǒng)網站開發(fā)、集團公司官網建設、成都外貿網站建設公司、高端網站制作、響應式網頁設計等建站業(yè)務,價格優(yōu)惠性價比高,為阜城等各大城市提供網站開發(fā)制作服務。

1、列表清單扁平化

有時你不確定列表的嵌套深度,而且只想全部要素在單個平面列表中。

可以通過以下方式獲得:

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、列表取樣

通過使用random軟件庫,以下代碼從給定的列表中生成了n個隨機樣本。

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

強烈推薦使用secrets軟件庫生成用于加密的隨機樣本。

以下代碼僅限用于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ù)字化

以下代碼將一個整數(shù)轉換為數(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ù)將檢查一個列表中的所有要素是否唯一。

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知識,請關注:Python自學網??!


當前名稱:創(chuàng)新互聯(lián)Python教程:有用的20個python代碼段(5)
當前路徑:http://www.dlmjj.cn/article/copcgoo.html