我不知道是否有辦法重新編寫下面的代碼列出理解。謝謝如何重寫爲循環列表理解
inputDict是一個字典
result = {}
for key in inputDict:
total = 0
for nodes in inputDict :
total = total + (key in inputDict[nodes])
result.update({key : total})
我不知道是否有辦法重新編寫下面的代碼列出理解。謝謝如何重寫爲循環列表理解
inputDict是一個字典
result = {}
for key in inputDict:
total = 0
for nodes in inputDict :
total = total + (key in inputDict[nodes])
result.update({key : total})
如果我理解正確的,你比你可以試試:
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]
不是一個列表理解,因爲你沒有建立一個列表。
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計數。
採用Counter
和chain
可以隱藏一些東西是怎麼回事,所以這裏是你會怎麼寫,沒有導入庫代碼:
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
的一部分。
它看起來並不代表我的代碼可以自己工作,你能更新你的代碼嗎? – 2014-09-03 04:42:46
_list comprehension_?你在這裏創建一個字典,而不是一個列表。 – 2014-09-03 04:43:44
你的代碼的哪部分不起作用? – 2014-09-03 04:49:31