【问题标题】:print dictionary minus two elements打印字典减去两个元素
【发布时间】:2017-05-05 15:42:54
【问题描述】:

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 个键\值对。我希望所有字典都打印除了以“数据包输出”或“字节”为键的两个键\值对。

有了这两行,每个键\值对都会被跳过,什么也不会打印。我根本不明白为什么。 “输入错误”与我的条件不匹配,因此应跳过 continue 并打印,依此类推,但匹配的两个键除外,应跳过它们。

我错过了什么?

谢谢。

【问题讨论】:

标签: python dictionary


【解决方案1】:
if k == 'packets output' or 'bytes'

这将始终评估为true,因为'bytes' 是一个真实值,您需要将k 与两者进行比较:

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

或者更Python化:

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

【讨论】:

  • 如果 OP 正在测试许多 ks 或更大组值中的成员资格,最好使用 set
【解决方案2】:
if len(errdict) == 21:
    for k, v in errdict.items():
        if k == 'packets output' or k == 'bytes':
            continue
        print(k, v)
    print()

【讨论】:

  • 如果您真正解释了为什么您的答案解决了 OP 的问题,这将有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
相关资源
最近更新 更多