2014-09-03 21 views
1

我不知道是否有辦法重新編寫下面的代碼列出理解。謝謝如何重寫爲循環列表理解

inputDict是一個字典

result = {} 
for key in inputDict: 
    total = 0 
    for nodes in inputDict : 
     total = total + (key in inputDict[nodes]) 
    result.update({key : total}) 
+3

它看起來並不代表我的代碼可以自己工作,你能更新你的代碼嗎? – 2014-09-03 04:42:46

+2

_list comprehension_?你在這裏創建一個字典,而不是一個列表。 – 2014-09-03 04:43:44

+0

你的代碼的哪部分不起作用? – 2014-09-03 04:49:31

回答

1

如果我理解正確的,你比你可以試試:

result = dict((key, sum(key in inputDict[nodes] for nodes in digraph)) for key in inputDict) 

或者,如果你需要一個列表:

result = [(key, sum(key in inputDict[nodes] for nodes in digraph)) for key in inputDict] 

或者:

result = [(key, sum(key in vals for nodes in digraph)) for key, vals in inputDict] 
+0

不錯的工作。很難像這樣思考。你有什麼建議如何學習Python列表的理解?謝謝。 – galaxyan 2014-09-03 04:56:29

+1

不客氣@我想,只是時間問題。它不像你想象的那麼困難,列出comprh只是簡單地寫'for循環'的一種方式,並且說實話不是唯一的方法。 – 2014-09-03 04:58:29

+2

它並不總是最好的方式。記住代碼清晰度是非常重要的。代碼一次寫入但讀取數百次。如果你的理解開始變得難以理解,那麼把它變成一個傳統的「for」區塊並沒有什麼錯, – IanAuld 2014-09-03 05:05:56

1

不是一個列表理解,因爲你沒有建立一個列表。

import collections 
import itertools 
result = collections.Counter(itertools.chain.from_iterable(inputDict.values())) 
:但是,你要執行這似乎是計算節點有多少鏈接到每個節點的操作,可以很容易地通過使用 collections.Counter計算每個節點有多少次出現在 inputDict值完成

itertools.chain需要inputDict.values()並將那裏的所有節點列表串成一個大的迭代器。 (或者也許這些都是節點集,很難說。)collections.Counter然後計算它看到每個元素的次數。結果是一個collections.Counter實例,其行爲大多像一個字典。有一些分歧,不過,如果你需要一個結果,這正是dict類型的,你可以調用它dict

result = dict(result) 

注意Counter返回0的計數不是在櫃檯物品,但dict不這樣做。如果您對其調用dict,則可能需要爲從未出現在inputDict.values()之間的節點填充0計數。


採用Counterchain可以隱藏一些東西是怎麼回事,所以這裏是你會怎麼寫,沒有導入庫代碼:

result = {} 

# Initialize counts to 0, to make sure nodes that don't appear in the values have the 
# right count and to make sure we don't need to check `if node in result` later. 
for node in inputDict: 
    result[node] = 0 

# Go through and count node occurrences. 
for adjacent_nodes in inputDict.values(): 
    for node in adjacent_nodes: 
     result[node] += 1 

沒有一個簡單的方法將其轉變爲理解而不會犧牲算法複雜性,這是爲什麼存在collections.Counter的一部分。