搜索列表的更好方法?任何建议表示赞赏:Python列表搜索
for key in nodelist.keys():
if len(nodelist[key]) > 0:
if key == "sample_node":
print key + ":"
print nodelist[key]
搜索列表的更好方法?任何建议表示赞赏:Python列表搜索
for key in nodelist.keys():
if len(nodelist[key]) > 0:
if key == "sample_node":
print key + ":"
print nodelist[key]
key = "sample_node"
if key in nodelist:
print ''.join([key, ":", nodelist[key]])
'if len()> 0'部分缺失... – EOL 2011-12-25 04:48:15
我把它当作他的天真方法来处理“如果字典中的这个项目被设置了”。 – Interrobang 2011-12-25 04:49:26
问题中的测试意味着“如果该值具有非零长度”,取而代之。例如,'nodelist = {“sample_node”:[]}'在原始问题中不会打印任何内容,但会在答案中打印出某些内容。 – EOL 2011-12-25 04:53:17
这是简单的写这个代码:
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
...和downvote的原因是...? – EOL 2011-12-25 04:53:47
您可能想要修复您的代码格式。 (在第一行有一个从未关闭的报价。) – FakeRainBrigand 2011-12-25 04:56:52
@FakeRainBrigand嘿人,只是编辑它不使用downvote;) – Efazati 2011-12-25 05:03:35
试试这个:
[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
如果nodelist
类型是dict
:
>>> key = 'sample_node'
>>> if nodelist.get(key):
... print key+':'+str(nodelist[key])
filter(lambda x: nodeList[x], nodeList)
你到底想干什么?用英文描述。准确**。如果您认为这将有所帮助,请举例说明预期的投入和产出。 – 2011-12-25 04:46:11
这不是“搜索”。这是一个“过滤器”。此外,'nodeList'不可能是一个列表,它必须是一个字典,这是有道理的。 – 2011-12-25 16:44:37