正在检索输出中的空列表,而不是值



我有以下代码,我想过滤掉那些小于阈值的值,并将其存储在一个变量中。但是下面的代码在输出中给出了一个空列表。

current_memory_available=29.373699550744604
total_memory=614480960
lst= {0: 602112, 1: 12852224, 2: 12992768, 3: 3211264, 4: 6717952, 5: 7012864, 6: 1605632, 7: 4391936, 8: 5571584, 9: 5571584, 10: 802816, 11: 6326272, 12: 11044864, 13: 11044864, 14: 401408, 15: 9840640, 16: 9840640, 17: 9840640, 18: 100352, 19: 100352, 20: 411074560, 21: 67141632, 22: 16392000}

passed = {key: (value/total_memory) * 100 for key,value in lst.items() if value < 
current_memory_available}
print(passed)

谢谢,非常感谢帮助

current_memory_available = 29.373699550744604
total_memory=614480960
dct = {0: 602112, 1: 12852224, 2: 12992768, 3: 3211264, 4: 6717952, 5: 7012864, 6: 1605632, 7: 4391936, 8: 5571584, 9: 5571584, 10: 802816, 11: 6326272, 12: 11044864, 13: 11044864, 14: 401408, 15: 9840640, 16: 9840640, 17: 9840640, 18: 100352, 19: 100352, 20: 411074560, 21: 67141632, 22: 16392000}
new_dct = {}
for key, value in dct.items():
calc = (value / total_memory) *100
if calc < current_memory_available:
new_dct[key] = value
print(new_dct)
dict理解中使用的

'if'语句永远不会为True,因为所有值都大于'current_memory_available'变量。因此,该词典被打印为null。

以下逻辑不正确:

passed = {key: (value/total_memory) * 100 for key,value in lst.items() if value < 
current_memory_available}

尝试使用以下内容:

passed = {key for key,value in lst.items() if (value/total_memory) * 100 < current_memory_available}

完整代码:

current_memory_available=29.373699550744604
total_memory=614480960
lst= {0: 602112, 1: 12852224, 2: 12992768, 3: 3211264, 4: 6717952, 5: 7012864, 6: 1605632, 7: 4391936, 8: 5571584, 9: 5571584, 10: 802816, 11: 6326272, 12: 11044864, 13: 11044864, 14: 401408, 15: 9840640, 16: 9840640, 17: 9840640, 18: 100352, 19: 100352, 20: 411074560, 21: 67141632, 22: 16392000}

passed = {key for key,value in lst.items() if (value/total_memory) * 100 < current_memory_available}
print(passed)

最新更新