搜索列表的更好方法是什么?任何建议表示赞赏:
for key in nodelist.keys():
if len(nodelist[key]) > 0:
if key == "sample_node":
print key + ":"
print nodelist[key]
答案 0 :(得分:4)
编写此代码更简单:
key = "sample_node"
if key in nodelist: # loop not needed, and .keys() not needed
value = nodelist[key]
if value: # len() not needed
print key + ":"
print value
答案 1 :(得分:2)
key = "sample_node"
if key in nodelist:
print ''.join([key, ":", nodelist[key]])
答案 2 :(得分:2)
如果nodelist
的类型为dict
:
>>> key = 'sample_node'
>>> if nodelist.get(key):
... print key+':'+str(nodelist[key])
答案 3 :(得分:1)
试试这个:
[k+':'+str(v) for k,v in nodelist.items() if k == 'sample_node' and v]
如果你只需要打印结果:
for s in (k+':'+str(v) for k,v in nodelist.items() if k == 'sample_node' and v):
print s
答案 4 :(得分:1)
filter( lambda x: nodeList[x], nodeList )