2011-12-25 199 views
-1

搜索列表的更好方法?任何建议表示赞赏:Python列表搜索

for key in nodelist.keys(): 
    if len(nodelist[key]) > 0: 
     if key == "sample_node": 
      print key + ":" 
      print nodelist[key] 
+5

你到底想干什么?用英文描述。准确**。如果您认为这将有所帮助,请举例说明预期的投入和产出。 – 2011-12-25 04:46:11

+0

这不是“搜索”。这是一个“过滤器”。此外,'nodeList'不可能是一个列表,它必须是一个字典,这是有道理的。 – 2011-12-25 16:44:37

回答

2
key = "sample_node" 
if key in nodelist: 
    print ''.join([key, ":", nodelist[key]]) 
+0

'if len()> 0'部分缺失... – EOL 2011-12-25 04:48:15

+1

我把它当作他的天真方法来处理“如果字典中的这个项目被设置了”。 – Interrobang 2011-12-25 04:49:26

+2

问题中的测试意味着“如果该值具有非零长度”,取而代之。例如,'nodelist = {“sample_node”:[]}'在原始问题中不会打印任何内容,但会在答案中打印出某些内容。 – EOL 2011-12-25 04:53:17

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 
+0

...和downvote的原因是...? – EOL 2011-12-25 04:53:47

+0

您可能想要修复您的代码格式。 (在第一行有一个从未关闭的报价。) – FakeRainBrigand 2011-12-25 04:56:52

+2

@FakeRainBrigand嘿人,只是编辑它不使用downvote;) – Efazati 2011-12-25 05:03:35

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 
+0

加一行为;) – Efazati 2011-12-25 04:58:11

+2

如果你认为'nodelist'是一个字典(通过使用'.items()'),那么你不需要for-loop:['k ='sample_node'; v = nodelist.get(k);如果v:print“%s:\ n%s”%(k,v)'](http://stackoverflow.com/a/8628297/4279) – jfs 2011-12-25 05:17:28

2

如果nodelist类型是dict

>>> key = 'sample_node' 
>>> if nodelist.get(key): 
...  print key+':'+str(nodelist[key]) 
1
filter(lambda x: nodeList[x], nodeList)