如何在Python中查找List字典的List中的值?

2024-04-19 03:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生。 我必须找到/比较一个字符串值和一个列表,这个列表存在于列表字典的列表中。我写了下面的代码,虽然它是工作良好,但我们可以写在一些更好的方式。你知道吗

abc = [{'GetDriverPackInfo_OUTPUT': {'OSList': [u'Linux', u'Windows', u'Xen', u'VMware'], 'ReturnValue': [u'0'], 'Version': [u'15.07.04']}}]

os_name = "Linux"

for k in abc:                   #['GetDriverPackInfo_OUTPUT']['OSList']:
    if os_name in k['GetDriverPackInfo_OUTPUT']['OSList']: #== os_name:
        print ("os_name found")
    else:
        print ("os_name not found")

Tags: 字符串代码namein列表output字典os
2条回答
In [1]: osname in [j for j in [k['GetDriverPackInfo_OUTPUT']['OSList'] for k in abc]][0]
Out[1]: True

如果返回True,则osname退出,否则不是。你知道吗

我不确定这对你有用。只有当abc总是有一个“GetDriverPackInfo\u OUTPUT”项时,它才会工作。你知道吗

temp=abc[0]['GetDriverPackInfo\u OUTPUT']['OSList']

如果操作系统名称在temp中:

  print "found"

其他:

  print "not found" 

相关问题 更多 >