collections模組中包含了很多常用的方法。如計數器、有序字典等。
a).counter方法是乙個計數器,用來記錄各個元素出現的次數:
from collections import counter
a ="123asdfssdgfgfjdfewwrw"
b =[2,
3,4,
5,6,
6,2,
2]print
(counter(a)
)counter(
)print
(counter(b)
)counter(
)
itertools是乙個迴圈器模組。
a).chain方法可以用於展平列表
from itertools import chain
a =[1,
2]b =[2,
5]print
(chain(a,b)
)#生成乙個迭代器
print
(list
(chain(a,b)))
#[1, 2, 2, 5]
print
(chain.from_iterable(
[a,b]))
#print
(list
(chain.from_iterable(
[a,b]))
)#[1, 2, 2, 5]
其他展平操作:
import torch
a = torch.tensor([1
,5])
b = torch.tensor([9
,5])
torch.cat(
(a,b)
)#tensor([1, 5, 9, 5])
print
(list
(torch.cat(
(a,b)
).numpy())
)#[1, 5, 9, 5]
#######################################
import numpy as np
c = np.array([[
1,2]
,[9,
10]])
print
(list
(c.flatten())
)#[1, 2, 9, 10]
tqdm是進度條模組
from tqdm import tqdm
import time
test_loader =[1
,2,3
,4,5
,9,10
]epochs =
8for epoch in
range(1
,epochs+1)
: data_bar = tqdm(test_loader)
for i in data_bar:
time.sleep(1)
data_bar.set_description(
'train epoch {}/{} '
.format
(epoch, epochs)
)
pipreqs模組用於生成python的依賴檔案requirement.txt,並能進行安裝
pipreqs ./-
-encoding=utf-8-
-force #生成依賴包版本
pip install -r requriements.txt #使用工程時,可以直接安裝
python中模組使用
模組使用 import random 匯入 import random as rdm 匯入後起別名 from random import randint 指定匯入 from random import randint as rint 指定匯入後起別名 as說明 使用as起別名後,中只能使用別名不在使...
Python集合模組 collections
是乙個函式,它用來建立乙個自定義的tuple物件,並且規定了tuple元素的個數,並可以用屬性而不是索引來引用tuple的某個元素。namedtuple 名稱 屬性list from collections import namedtuple point namedtuple point x y p...
Python中OS SYS 模組使用
os.getcwd 獲取當前工作目錄,即當前python指令碼工作的目錄路徑 os.chdir dirname 改變當前指令碼工作目錄 相當於shell下cd os.curdir 返回當前目錄 os.pardir 獲取當前目錄的父目錄字串名 os.makedirs dirname1 dirname2...