gpt4 book ai didi

python - 如何重写 for 循环以列表理解

转载 作者:行者123 更新时间:2023-12-01 05:03:02 26 4
gpt4 key购买 nike

我想知道是否有办法重新编写以下代码来列表理解。谢谢您

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]

关于python - 如何重写 for 循环以列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25636351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com