打印字典减去两个元素

2024-04-27 04:53:47 发布

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

Python 3.6版

所有调试输出都来自PyCharm 2017.1.2

我有一个程序可以访问代码的这一部分:

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个键值对。我想打印所有的字典,除了以“packets output”或“bytes”为键的两个键值对。你知道吗

在这两行中,每个键值对都会被跳过,而不会打印任何内容。我就是不明白为什么“输入错误”与我的条件不匹配,因此应跳过continue并打印它,以此类推,但两个键不匹配且应跳过。你知道吗

我错过了什么?你知道吗

谢谢你。你知道吗


Tags: orinputoutputlenif字典bytesint
2条回答
if len(errdict) == 21:
    for k, v in errdict.items():
        if k == 'packets output' or k == 'bytes':
            continue
        print(k, v)
    print()
if k == 'packets output' or 'bytes'

这将始终计算为true,因为'bytes'是真实值,您需要将k与以下两者进行比较:

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

或更具脓性:

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

相关问题 更多 >