2017-08-17 72 views
3

我正在查找Hellinger之間的分佈之間的距離的一些公式,我發現一個(在Python中),我從來沒有見過類似的格式。我很困惑它是如何工作的。Python Hellinger公式解釋

def hellinger(p,q): 
    """Hellinger distance between distributions""" 
    return sum([(sqrt(t[0])-sqrt(t[1]))*(sqrt(t[0])-sqrt(t[1]))\ 
       for t in zip(p,q)])/sqrt(2.) 

我從來沒有見過這種...格式。他們被一個for語句分開?我的意思是......這是甚麼工作?

+2

這constuct被命名爲[列表理解(https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)並且反斜槓用於續行。 – MaxPowers

+0

Ohhhhhhhhhhhhhhhhhhhh這不是一個正斜槓 - 我是一個白癡,我很困惑。感謝您指出了這一點。 雖然這並不能解除我的困惑 - 只有新的問題出現。 't'是在for語句中定義的,但它出現在它之前...... python如何支持它? – user3026388

+1

查看以上鍊接到列表理解文檔。然後你會明白它是如何工作的。 – MaxPowers

回答

1

對於距離測量我有一個弱點,因此我做了一個notebook的Hellinger距離的一些實現。

關於你的問題,這個結構被稱爲list comrehension,反斜槓只是爲了續行。

這裏是沒有列表的理解可能上市:

def hellinger_explicit(p, q): 
    """Hellinger distance between two discrete distributions. 
     Same as original version but without list comprehension 
    """ 
    list_of_squares = [] 
    for p_i, q_i in zip(p, q): 

     # caluclate the square of the difference of ith distr elements 
     s = (math.sqrt(p_i) - math.sqrt(q_i)) ** 2 

     # append 
     list_of_squares.append(s) 

    # calculate sum of squares 
    sosq = sum(list_of_squares)  

    return sosq/math.sqrt(2)