[英]Sorting a dictionary by its value, and then its key if values are equal then outputting a list
[英]Printing the values of a dictionary when its key is equal to the value of a list element
我下面有这段代码,我想为等于numb[i]
组合中的任何combo[keys]
打印combo[values]
numb[i]
numb = [5, 7, 49, 11, 13]
combo = {45 : (-1002,-1023), 49 : (-9999,-2347), 20 : (-1979, -1576), 13 : (-6000,-3450), 110 : (-2139, -8800), 7 : (-6754,-9087) }
请问我该怎么做?
您的意思是循环numb
并打印任何键(如果存在)?
两种选择; 循环:
for key in numb:
if key in combo:
print combo[key]
也可以表示为列表理解,以生成列表:
[combo[key] for key in numb if key in combo]
或具有字典视图 :
for key in combo.viewkeys() & numb:
print combo[key]
再次作为列表理解:
[combo[key] for key in combo.viewkeys() & numb]
演示:
>>> numb = [5, 7, 49, 11, 13]
>>> combo = {45 : (-1002,-1023), 49 : (-9999,-2347), 20 : (-1979, -1576), 13 : (-6000,-3450), 110 : (-2139, -8800), 7 : (-6754,-9087) }
>>> [combo[key] for key in numb if key in combo]
[(-6754, -9087), (-9999, -2347), (-6000, -3450)]
>>> [combo[key] for key in combo.viewkeys() & numb]
[(-9999, -2347), (-6000, -3450), (-6754, -9087)]
您采取的路线取决于combo
和numb
的大小,以及是否也可以set
numb
。 如果可以设置numb
,则dict.viewkeys()
可以通过使用两者中的较小者来优化交集操作,并且很有可能是较快的选项,尤其是对于较大的数据集。
这可以通过简单的列表理解来完成:
>>> [v for k, v in combo.items() if k in numb]
[(-6754, -9087), (-6000, -3450), (-9999, -2347)]
我想那是你的意思?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.