我不知道是否有办法重新编写下面的代码列出理解。谢谢如何重写为循环列表理解
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