2017-05-05 86 views
-1

的Python 3.6打印字典减去两个元件

所有调试输出是从2017年1月2日PyCharm

我有一个程序,获取到码的这一部分:

if len(errdict) == 21: 
    for k, v in errdict.items(): 
     if k == 'packets output' or 'bytes': 
      continue 
     print(k, v) 
    print() 

的值k:和errdict {}在执行时如下:

k={str}'input errors' 

__len__ = {int} 21 
'CRC' (73390624) = {int} 0 
'babbles' (73390464) = {int} 0 
'bytes' (73390496) = {int} 0 
'collisions' (73455360) = {int} 0 
'deferred' (73455440) = {int} 0 
'frame' (73390592) = {int} 0 
'ignored' (73390688) = {int} 0 
'input errors' (73455280) = {int} 0 
'input packets with dribble condition detected' (63021088) = {int} 0 
'interface resets' (73451808) = {int} 0 
'late collision' (73455400) = {int} 0 
'lost carrier' (73455520) = {int} 0 
'no carrier' (73455480) = {int} 0 
'output buffer failures' (73451856) = {int} 0 
'output buffers swapped out' (73055328) = {int} 0 
'output errors' (73455120) = {int} 0 
'overrun' (73390112) = {int} 0 
'packets output' (73455320) = {int} 0 
'underruns' (73455080) = {int} 0 
'unknown protocol drops' (73451904) = {int} 0 
'watchdog' (73455160) = {int} 0 

如果我删除这两行:

 if k == 'packets output' or 'bytes': 
      continue 

它正确打印出字典的所有21个键\值对。我希望所有字典都能打印,除了包含'数据包输出'或'字节'作为关键字的两个键\值对。

有了这两行,每个键\值对都被跳过而没有打印出来。我根本不明白为什么。 '输入错误'与我的条件不匹配,所以继续应该被跳过并且应该打印,除了两个匹配的键之外的其他行都应该打印,并且应该跳过它们。

我错过了什么?

谢谢。

+1

'。 ..或k =='bytes'' –

+1

尝试:'如果k =='数据包输出'或k =='字节':' –

+0

尼克A,莫里斯迈尔和韦格拉塔 - 谢谢你。这就是我错过的。我只是用修复程序再次运行我的程序,它的行为正确。 – MarkS

回答

7
if k == 'packets output' or 'bytes' 

这将始终评估为true作为'bytes'是truthy值,你需要比较k既:

if k == 'packets output' or k == 'bytes' 

或者更pythonically:

if k in ['packets output', 'bytes'] 
+0

如果OP正在测试很多'k'或者更大的一组值中的成员,那么更好的办法是使用'set'。 – blacksite

0
if len(errdict) == 21: 
    for k, v in errdict.items(): 
     if k == 'packets output' or k == 'bytes': 
      continue 
     print(k, v) 
    print() 
+1

如果你真的解释了为什么你的答案解决了OP的问题,这将有所帮助。 – kdopen