2014-09-03 20 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的一部分。