[英]meaning of comma operator in python
我理解了 Python 中有關逗號運算符的簡單概念。 例如,
x0, sigma = 0, 0.1
表示 x0=0,sigma=0.1。 但是我獲得了一個代碼,其中有一行如下所示。
y, xe = np.histogram(np.random.normal(x0, sigma, 1000))
其中 y 和 xe 的輸出如下。
y
Out[10]: array([ 3, 17, 58, 136, 216, 258, 189, 87, 31, 5], dtype=int64)
xe
Out[11]:
array([-0.33771565, -0.27400243, -0.21028922, -0.146576 , -0.08286279,
-0.01914957, 0.04456364, 0.10827686, 0.17199007, 0.23570329,
0.2994165 ])
我不知道如何閱讀 y, xe 表達式。 我能查到什么來理解它在說什么?
x0, sigma = 0, 0.1
是語法糖。 有些事情正在幕后發生:
0, 0.1
隱式地創建了一個包含兩個元素的元組。
x0, sigma =
將該元組解包為這兩個變量。
如果您查看numpy.histogram
的文檔,您會看到它返回以下兩件事:
hist : array
The values of the histogram. See density and weights for a description of the possible semantics.
bin_edges : array of dtype float
Return the bin edges (length(hist)+1).
您的y, xe = ...
解包了兩個返回數組的元組。 這就是為什么你的y
被分配給一個 numpy int64 數組而你的xe
被分配給一個 numpy float 數組。
逗號形成一個tuple ,它在 Python 中看起來就像一個不可變的列表。
Python 執行解構賦值,在其他一些語言中可以找到,例如現代 JavaScript。 簡而言之,單個賦值可以將多個左側變量映射到相同數量的右側值:
foo, bar = 1, 2
這相當於一次性完成foo = 1
和bar = 2
。 這可用於交換值:
a, b = b, a
您可以在右側使用元組或列表,如果長度匹配,它將以相同的方式解包(解構):
a, b = [1, 2]
# same effect as above:
xs = [1, 2]
a, b = xs
# again, same effect using a tuple:
ys = 1, 2
a, b = ys
您可以從函數返回一個元組或一個列表,並立即解構結果:
def foo():
return (1, 2, 3) # Parens just add readability
a, b, c = foo() # a = 1; b = 2; c = 3
我希望這回答了你的問題。 直方圖函數返回一個解包的 2 元組。
這可能是您的解決方案:
def func():
return 'a', 3, (1,2,3) # returns a tuple of 3 elements (str, int, tuple)
x1, x2, x3 = func() # unpacks the tuple of 3 elements into 3 vars
# x1: 'a'
# x2: 3
# x3: (1,2,3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.