Python 循环,而数组具有具有特定值的元素
假设我有一个设备列表,我需要检查它们的状态,然后脚本才能继续。简单地说,它可以如下所示:Python 循环,而数组具有具有特定值的元素,python,Python,假设我有一个设备列表,我需要检查它们的状态,然后脚本才能继续。简单地说,它可以如下所示: devices = { 'dev1': {'ready':False, ...}, 'dev2': {'ready':False, ...}, 'dev3': {'ready':False, ...} } while /exists device with 'ready' == False/: ... some code scanning for devices ...
devices = {
'dev1': {'ready':False, ...},
'dev2': {'ready':False, ...},
'dev3': {'ready':False, ...}
}
while /exists device with 'ready' == False/:
... some code scanning for devices ...
if /device ready/:
devices[devX]['ready'] = True
我不知道while语句中的条件应该是什么样子
我找到的最接近的解决方案是:
len([d for d in devices if d['ready'] == True]) > 0
但它给了我TypeError:字符串索引必须是整数,而不是str
你能告诉我吗?在你的代码中,你有
d
迭代每个键入设备(不是每个值)。这就是为什么d['ready']
不起作用的原因:d
是一个字符串,类似于'dev1'
。您可以使用来迭代这些值
如果要检查设备中的任何值是否准备就绪,可以使用:
如果要检查它们是否都准备好了,可以使用:
问题是设备中d的只返回dict的键。请将行更改为
len([d for d, v in devices.items() if v['ready'] == True]) > 0
伟大的这帮了大忙!谢谢你,我离你很近;)谢谢,那也行!
if all(x['ready'] for x in devices.values()):
len([d for d, v in devices.items() if v['ready'] == True]) > 0