我现在有一本字典,它是这样的:
{OctetString('Ethernet8/6'): Integer(1),
OctetString('Ethernet8/7'): Integer(2),
OctetString('Ethernet8/8'): Integer(2),
OctetString('Ethernet8/9'): Integer(1),
OctetString('Vlan1'): Integer(2),
OctetString('Vlan10'): Integer(1),
OctetString('Vlan15'): Integer(1),
OctetString('loopback0'): Integer(1),
OctetString('mgmt0'): Integer(1),
OctetString('port-channel1'): Integer(1),
OctetString('port-channel10'): Integer(1),
OctetString('port-channel101'): Integer(1),
OctetString('port-channel102'): Integer(1)}
我希望我的字典是这样的:
^{pr2}$我不确定找到这些键、值对的最佳方法是什么。我真的想要与'\Ethernet(\d*)/(\d*)匹配的任何内容。不过,我不确定最好的解决办法。我的主要目标是匹配所有以太网值,然后进行计数。例如:当dict匹配所有Ethernetx/x之后,我想计算1和2的数量
另外,为什么我迭代字典并打印时只得到Ethernet8/6,但当我打印字典时,我最终得到的是OctetString('Ethernet8/6')?在
for k in snmp_comb: print k
Ethernet2/18
Ethernet2/31
Ethernet2/30
Ethernet2/32
Ethernet8/46
(我将使用与接受答案相同的
'Ethernet' in str(key)
测试。)如果您想保留原始dict并将过滤后的版本作为单独的字典,我将使用一个理解:
如果您不想保留原来的dict,也可以删除不需要的条目:
^{pr2}$得到“OctetString('…')”的原因与此相同:
前两个测试向您展示了一个可以在源代码中使用的表示,这就是为什么会有引号。这就是
repr
函数的作用。第三个测试打印的是正常乐趣的值,因此不添加引号。“OctetString('…')”也只是这样一种表示,您可以复制并粘贴到源代码中,然后再次获得实际的OctetString对象,而不是Python字符串对象。我想pprint
主要用于开发,在开发中获得完整的repr
版本更有用。在这应该做到:
使用
print
时,python调用OctetString
对象上的__str__
方法,该方法返回Ethernet8/6
。但是,我认为pprint
默认为打印对象类型。在编辑:
stefanpochmann在下面正确地指出,
if 'Ethernet' in
将匹配包含单词Ethernet
的任何字符串。OP在他的帖子中提到过使用regex来匹配Ethernet(\d*)/(\d*)
,因此这个答案可能不适合任何其他想要解决类似问题的人。在相关问题 更多 >
编程相关推荐