- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一本字典,它的值是字典。以下是我的字典结构
myD = {'key1': {'x' : 123, 'y' : 432},
'key2': {'x' : 456, 'y' : 565},
'key3': {'x' : 789, 'y' : 420},
...}
我需要比较这个字典的值(如你所见,我在每个值中都有相似的字典结构)并生成以下输出。策略是遍历值字段中的每个字典并选择给定键的最小值并将其插入到新字典中。例如,如果我们考虑值字典中的 x 键,它的最小值是 123
。所以我的新字典应该有 x:123
。
my_newD = {'x' : 123, 'y' : 420, ...}
我可以使用 3 个 for 循环来实现这一点,但是有什么优雅的方法可以用更少的 for 循环来做到这一点吗?
最佳答案
这是一个使用 collections.defaultdict
的 O(n) 解决方案:
from collections import defaultdict
myD = {'key1': {'x' : 123, 'y' : 432},
'key2': {'x' : 456, 'y' : 565},
'key3': {'x' : 789, 'y' : 420}}
# initialise defaultdict of lists
d = defaultdict(list)
# iterate input dictionary and add values to lists
for v1 in myD.values():
for k2, v2 in v1.items():
d[k2].append(v2)
# calculate minimum
res = {k: min(v) for k, v in d.items()}
print(res)
{'x': 123, 'y': 420}
关于python - 比较具有较少循环的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971429/
我正在使用Visual Studio 2012和Web Essential 2012,而Less生成的css与预期的不一样 //style.less .selector{ max-heig
我创建了一个基于LESS的小型混合器,用于以标准或视网膜格式输出图像。我无法理解将变量包装在与此相伴的一些CSS URL中-当我编译下面的代码时,我最终得到 url('http://sample.co
有人可以帮助我使用 CSS(less)吗,因为我似乎还不能理解它是如何工作的,我已经通过 node.js 安装了它,但现在如何将它链接到我的代码/网页? 由于某种原因,选择框没有输出到网页上,因为很可
我知道大多数算术运算只能使用按位运算符( Add two integers using only bitwise operators? 、 Multiplication of two integers
我需要在 less 中选择一个类的第 n 个子元素,而不是计算特定类的元素。例如,给定: 李 li class="skip_this" 李 李 李 我想让第 n 个 child 在计数时跳过 skip
当我单击一个按钮时,我进行了一个 ajax 调用,该调用将不同的 html 代码加载到一个 ID 为“main”的 div 中。我可以毫无问题地显示 html 代码,但我找不到将 css 和 js 代
我正在使用非常有限的 Shell 开发嵌入式 Linux。内置命令非常少。 我想检查 gpio 端口。这适用于以下内容。但它需要很多 CPU/IO - 电源!!所以我想像 sleep 一样得到短暂的休
我是一名优秀的程序员,十分优秀!