本文目錄一覽:
- 1、Python常用函數三有哪些?這7個函數使用頻率最高,總算搞明白了
- 2、Python基礎 numpy中的常見函數有哪些
- 3、python 十條函數
- 4、pytorch 常用函數參數詳解
- 5、68 個 Python 內置函數詳解
- 6、python3.4學習筆記 3.x和2.x的區別,持續更新
Python常用函數三有哪些?這7個函數使用頻率最高,總算搞明白了
1.1 例如:print(hex(2))案例
1.2 輸出函數:print(hex(2))
1.3 輸出結果:0x2
1.4 解析說明:返回16進位的數。
2.1 例如:print(chr(10))案例
2.2 輸出函數:print(chr(10))
2.3 輸出結果:0o12
2.4 解析說明:返回當前整數對應的ASCll碼
3.1 例如:print(ord(“b”))案例
3.2 輸出函數:print(ord(“b”))
3.3 輸出結果:98
3.4 解析說明:返回當前ASCll碼的10進位數
4.1 例如:print(chr(97))
4.2 輸出函數:print(chr(97))
4.3 輸出結果:b
4.4 解析說明:返回當前ASCll碼的10進位數。
案例一:給你一個字元串,s = ‘hello kitty’
1.1 輸出函數:print(s.capitalize())
1.2 輸出結果:0x2
1.3 解析說明:返回16進位的數。
2.1輸出函數:print(s.replace(‘kitty’,’kuang’))
2.2 輸出結果:hello kuang
2.3 解析說明:替換功能,將kitty換成kuang。
2.4 輸出函數:print(s.replace(‘4′,’KK’))
2.5 輸出結果:12KK12KK
2.6 解析說明:所有的4都替換成KK
2.7 輸出函數:print(s.replace(‘4′,’KK’))
2.8 輸出結果:12KK12KK124
2.9 解析說明:將前兩個的4替換成go
案例一:給你一個字元串,ip = ‘192.168.1.1’
3.1 輸出函數:print(ip.split(‘,’))
3.2 輸出結果:[‘192.168.1.1’]
3.3 解析說明:將字元串分割成列表
案例一:給你一個字元串,ip = ‘192.168.1.1’
3.3 輸出函數:print(ip.split(‘,’,2))
3.4 輸出結果:[‘192.168.1.1’]
3.5 解析說明:從第二個開始分割成列表
Python基礎 numpy中的常見函數有哪些
有些Python小白對numpy中的常見函數不太了解,今天小編就整理出來分享給大家。
Numpy是Python的一個科學計算的庫,提供了矩陣運算的功能,其一般與Scipy、matplotlib一起使用。其實,list已經提供了類似於矩陣的表示形式,不過numpy為我們提供了更多的函數。
數組常用函數
1.where()按條件返回數組的索引值
2.take(a,index)從數組a中按照索引index取值
3.linspace(a,b,N)返回一個在(a,b)範圍內均勻分布的數組,元素個數為N個
4.a.fill()將數組的所有元素以指定的值填充
5.diff(a)返回數組a相鄰元素的差值構成的數組
6.sign(a)返回數組a的每個元素的正負符號
7.piecewise(a,[condlist],[funclist])數組a根據布爾型條件condlist返回對應元素結果
8.a.argmax(),a.argmin()返回a最大、最小元素的索引
改變數組維度
a.ravel(),a.flatten():將數組a展平成一維數組
a.shape=(m,n),a.reshape(m,n):將數組a轉換成m*n維數組
a.transpose,a.T轉置數組a
數組組合
1.hstack((a,b)),concatenate((a,b),axis=1)將數組a,b沿水平方向組合
2.vstack((a,b)),concatenate((a,b),axis=0)將數組a,b沿豎直方向組合
3.row_stack((a,b))將數組a,b按行方向組合
4.column_stack((a,b))將數組a,b按列方向組合
數組分割
1.split(a,n,axis=0),vsplit(a,n)將數組a沿垂直方向分割成n個數組
2.split(a,n,axis=1),hsplit(a,n)將數組a沿水平方向分割成n個數組
數組修剪和壓縮
1.a.clip(m,n)設置數組a的範圍為(m,n),數組中大於n的元素設定為n,小於m的元素設定為m
2.a.compress()返回根據給定條件篩選後的數組
數組屬性
1.a.dtype數組a的數據類型
2.a.shape數組a的維度
3.a.ndim數組a的維數
4.a.size數組a所含元素的總個數
5.a.itemsize數組a的元素在內存中所佔的位元組數
6.a.nbytes整個數組a所佔的內存空間7.a.astype(int)轉換a數組的類型為int型
數組計算
1.average(a,weights=v)對數組a以權重v進行加權平均
2.mean(a),max(a),min(a),middle(a),var(a),std(a)數組a的均值、最大值、最小值、中位數、方差、標準差
3.a.prod()數組a的所有元素的乘積
4.a.cumprod()數組a的元素的累積乘積
5.cov(a,b),corrcoef(a,b)數組a和b的協方差、相關係數
6.a.diagonal()查看矩陣a對角線上的元素7.a.trace()計算矩陣a的跡,即對角線元素之和
以上就是numpy中的常見函數。更多Python學習推薦:PyThon學習網教學中心。
python 十條函數
def age():
“””This funcation aske user’s age and return a interge
n=int(input(‘Please input your age:’))
return n
…
就這樣寫好了,沒時間玩這麼簡單的東西。
pytorch 常用函數參數詳解
1、torch.cat(inputs, dim=0) – Tensor
參考鏈接:
[Pytorch] 詳解 torch.cat()
Pytorch學習筆記(一):torch.cat()模塊的詳解
函數作用:cat 是 concatnate 的意思:拼接,聯繫在一起。在給定維度上對輸入的 Tensor 序列進行拼接操作。torch.cat 可以看作是 torch.split 和 torch.chunk 的反操作
參數:
inputs(sequence of Tensors):可以是任意相同類型的 Tensor 的 python 序列
dim(int, optional):defaults=0
dim=0: 按列進行拼接
dim=1: 按行進行拼接
dim=-1: 如果行和列數都相同則按行進行拼接,否則按照行數或列數相等的維度進行拼接
假設 a 和 b 都是 Tensor,且 a 的維度為 [2, 3],b 的維度為 [2, 4],則
torch.cat((a, b), dim=1) 的維度為 [2, 7]
2、torch.nn.CrossEntropyLoss()
函數作用:CrossEntropy 是交叉熵的意思,故而 CrossEntropyLoss 的作用是計算交叉熵。CrossEntropyLoss 函數是將 torch.nn.Softmax 和 torch.nn.NLLLoss 兩個函數組合在一起使用,故而傳入的預測值不需要先進行 torch.nnSoftmax 操作。
參數:
input(N, C):N 是 batch_size,C 則是類別數,即在定義模型輸出時,輸出節點個數要定義為 [N, C]。其中特別注意的是 target 的數據類型需要是浮點數,即 float32
target(N):N 是 batch_size,故 target 需要是 1D 張量。其中特別注意的是 target 的數據類型需要是 long,即 int64
例子:
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True, dtype=torch.float32)
target = torch.empty(3, dtype=torch.long).random_(5)
output = loss(input, target)
output
輸出為:
tensor(1.6916, grad_fn=NllLossBackward)
68 個 Python 內置函數詳解
內置函數就是Python給你提供的,拿來直接用的函數,比如print.,input等。
截止到python版本3.6.2 ,python一共提供了68個內置函數,具體如下
本文將這68個內置函數綜合整理為12大類,正在學習Python基礎的讀者一定不要錯過,建議收藏學習!
(1)列表和元組
(2)相關內置函數
(3)字元串
frozenset 創建一個凍結的集合,凍結的集合不能進行添加和刪除操作。
語法:sorted(Iterable, key=函數(排序規則), reverse=False)
語法:fiter(function. Iterable)
function: 用來篩選的函數. 在filter中會自動的把iterable中的元素傳遞給function. 然後根據function返回的True或者False來判斷是否保留留此項數據 , Iterable: 可迭代對象
搜索公眾號頂級架構師後台回復「面試」,送你一份驚喜禮包。
語法 : map(function, iterable)
可以對可迭代對象中的每一個元素進行映射. 分別去執行 function
hash : 獲取到對象的哈希值(int, str, bool, tuple). hash演算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空間換的時間 比較耗費內存
python3.4學習筆記 3.x和2.x的區別,持續更新
python3.4學習筆記(四) 3.x和2.x的區別
在2.x中:print html,3.x中必須改成:print(html)
import urllib2
ImportError: No module named ‘urllib2’
在python3.x裡面,用urllib.request代替urllib2
import thread
ImportError: No module named ‘thread’
在python3.x裡面,用_thread(在前面加一個下劃線)代替thread
在2.x中except Exception,e : 3.x中改為except (Exception):
=================================
print函數
雖然print語法是Python 3中一個很小的改動,且應該已經廣為人知,但依然值得提一下:Python 2中的print語句被Python 3中的print()函數取代,這意味著在Python 3中必須用括弧將需要輸出的對象括起來。
在Python 2中使用額外的括弧也是可以的。但反過來在Python 3中想以Python2的形式不帶括弧調用print函數時,會觸發SyntaxError。
Python 2.7.6
print ‘Python’, python_version()
print ‘Hello, World!’
print(‘Hello, World!’)
print “text”, ; print ‘print more text on the same line’
輸出:
Hello, World!
Hello, World!
text print more text on the same line
—————————
Python 3.4.1
print(‘Python’, python_version())
print(‘Hello, World!’)
print(“some text,”, end=””)
print(‘ print more text on the same line’)
輸出:
Hello, World!
some text, print more text on the same line
print ‘Hello, World!’
File “ipython-input-3-139a7c5835bd”, line 1
print ‘Hello, World!’
^
SyntaxError: invalid syntax
注意:在Python中,帶不帶括弧輸出」Hello World」都很正常。
但如果在圓括弧中同時輸出多個對象時,就會創建一個元組,這是因為在Python 2中,print是一個語句,而不是函數調用。
print ‘Python’, python_version()
print(‘a’, ‘b’)
print ‘a’, ‘b’
Python 2.7.7
(‘a’, ‘b’)
a b
———————————
整數除法
由於人們常常會忽視Python 3在整數除法上的改動(寫錯了也不會觸發Syntax Error),所以在移植代碼或在Python 2中執行Python 3的代碼時,需要特別注意這個改動。
所以,我還是會在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來避免代碼在Python
2環境下可能導致的錯誤(或與之相反,在Python 2腳本中用from __future__ import division來使用Python
3的除法)。
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
———————————
Unicode
Python 2有基於ASCII的str()類型,其可通過單獨的unicode()函數轉成unicode類型,但沒有byte類型。
而在Python 3中,終於有了Unicode(utf-8)字元串,以及兩個位元組類:bytes和bytearrays。
Python 2.7.6
print type(unicode(‘this is like a python3 str type’))
type ‘unicode’
print type(b’byte type does not exist’)
type ‘str’
print ‘they are really’ + b’ the same’
they are really the same
print type(bytearray(b’bytearray oddly does exist though’))
type ‘bytearray’
Python 3.4.1 has class ‘bytes’
print(‘and Python’, python_version(), end=””)
print(‘ also has’, type(bytearray(b’bytearrays’)))
and Python 3.4.1 also has class ‘bytearray’
1
‘note that we cannot add a string’ + b’bytes for data’
—————————————————————————
TypeError Traceback (most recent call last)
ipython-input-13-d3e8942ccf81 in module()
—- 1 ‘note that we cannot add a string’ + b’bytes for data’
TypeError: Can’t convert ‘bytes’ object to str implicitly
=================================
python 2.4 與 python 3.0 的比較
一、 print 從語句變為函數
原: print 1,2+3
改為: print ( 1,2+3 )
二、range 與 xrange
原 : range( 0, 4 ) 結果 是 列表 [0,1,2,3 ]
改為:list( range(0,4) )
原 : xrange( 0, 4 ) 適用於 for 循環的變數控制
改為:range(0,4)
三、字元串
原: 字元串以 8-bit 字元串存儲
改為: 字元串以 16-bit Unicode 字元串存儲
四、try except 語句的變化
在2.x中except Exception,e : 3.x中改為except (Exception):
五、打開文件
原: file( ….. )
或 open(…..)
改為:
只能用 open(…..)
六、從鍵盤錄入一個字元串
原: raw_input( “提示信息” )
改為: input( “提示信息” )
七、bytes 數據類型
A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 = x 256.
bytes 可以看成是「位元組數組」對象,每個元素是 8-bit 的位元組,取值範圍 0~255。
由於在 python 3.0中字元串以 unicode 編碼存儲,當寫入二進位文件時,字元串無法直接寫入(或讀取),必須以某種方式的編碼為位元組序列後,方可寫入。
(一)字元串編碼(encode) 為 bytes
例: s = “張三abc12”
b = s.encode( 編碼方式)
# b 就是 bytes 類型的數據
# 常用的編碼方式為 : “uft-16” , “utf-8”, “gbk”, “gb2312”, “ascii” , “latin1” 等
# 注 : 當字元串不能編碼為指定的「編碼方式」時,會引發異常
(二) bytes 解碼(decode)為字元串
s = “張三abc12”
b = s.encode( “gbk”) # 字元串 s 編碼為 gbk 格式的位元組序列
s1 = b.decode(“gbk”) # 將位元組序列 b以gbk格式 解碼為字元串
# 說明,當位元組序列不能以指定的編碼格式解碼時會引發異常
(三)使用方法舉例
#coding=gbk
f = open(“c:\\1234.txt”, “wb”)
s = “張三李四abcd1234”
# ——————————-
# 在 python2.4 中我們可以這樣寫:
# f.write( s )
# 但在 python 3.0中會引發異常
# ——————————-
b = s.encode(“gbk”)
f.write( b )
f.close()
input(“?”)
讀取該文件的例子:
#coding=gbk
f = open(“c:\\1234.txt”, “rb”)
f.seek(0,2) #定位至文件尾
n = f.tell() #讀取文件的位元組數
f.seek(0,0) #重新定位至文件開始處
b = f.read( n )
# ——————————
# 在 python 2.4 中 b 是字元串類型
# 要 python 3.0 中 b 是 bytes 類型
# 因此需要按指定的編碼方式確碼
# ——————————
s = b.decode(“gbk”)
print ( s )
# ——————————
# 在 python 2.4 中 可以寫作 print s 或 print ( s )
# 要 python 3.0 中 必須寫作 print ( s )
# ——————————
f.close()
input(“?”)
運行後應顯示:
張三李四abcd1234
(四) bytes序列,一但形成,其內容是不可變的,例:
s=”ABCD”
b=s.encode(“gbk”)
print b[0] # 顯示 65
b[0] = 66
# 執行該句,出現異常: ‘bytes’ object does not support item assignment
八、 chr( K ) 與 ord( c )
python 2.4.2以前
chr( K ) 將編碼K 轉為字元,K的範圍是 0 ~ 255
ord( c ) 取單個字元的編碼, 返回值的範圍: 0 ~ 255
python 3.0
chr( K ) 將編碼K 轉為字元,K的範圍是 0 ~ 65535
ord( c ) 取單個字元的編碼, 返回值的範圍: 0 ~ 65535
九、 除法運算符
python 2.4.2以前
10/3 結果為 3
python 3.0
10 / 3 結果為 3.3333333333333335
10 // 3 結果為 3
十、位元組數組對象 — 新增
(一) 初始化
a = bytearray( 10 )
# a 是一個由十個位元組組成的數組,其每個元素是一個位元組,類型借用 int
# 此時,每個元素初始值為 0
(二) 位元組數組 是可變的
a = bytearray( 10 )
a[0] = 25
# 可以用賦值語句更改其元素,但所賦的值必須在 0 ~ 255 之間
(三) 位元組數組的切片仍是位元組數組
(四) 字元串轉化為位元組數組
#coding=gbk
s =”你好”
b = s.encode( “gbk”) # 先將字元串按某種「GBK」編碼方式轉化為 bytes
c = bytearray( b ) #再將 bytes 轉化為 位元組數組
也可以寫作
c = bytearray( “你好”, “gbk”)
(五) 位元組數組轉化為字元串
c = bytearray( 4 )
c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68
s = c.decode( “gbk” )
print ( s )
# 應顯示: ABCD
(六) 位元組數組可用於寫入文本文件
#coding=gbk
f = open(“c:\\1234.txt”, “wb”)
s = “張三李四abcd1234”
# ——————————-
# 在 python2.4 中我們可以這樣寫:
# f.write( s )
# 但在 python 3.0中會引發異常
# ——————————-
b = s.encode(“gbk”)
f.write( b )
c=bytearray( “王五”,”gbk”)
f.write( c )
f.close()
input(“?”)
原創文章,作者:JCYZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/139310.html