【问题标题】:snmpwalk : get list of integers not stringsnmpwalk :获取整数列表而不是字符串
【发布时间】:2016-06-08 10:05:15
【问题描述】:

在我的 python 脚本中,我获取了 5 个 OID,每个 OID 返回一个整数 这是我的代码:

OIDs = []
res = []

OIs.append(netsnmp.VarList(netsnmp.Varbind('1.3.6.1.4.1.45.1.1.4.1')))
OIs.append(netsnmp.VarList(netsnmp.Varbind('1.3.6.1.4.1.45.1.1.4.2')))
OIs.append(netsnmp.VarList(netsnmp.Varbind('1.3.6.1.4.1.45.1.1.4.3')))
OIs.append(netsnmp.VarList(netsnmp.Varbind('1.3.6.1.4.1.45.1.1.4.4')))
OIs.append(netsnmp.VarList(netsnmp.Varbind('1.3.6.1.4.1.45.1.1.3.1')))

for i in range(len(OIDs)):
    res.append(netsnmp.snmpwlak(OIDs[i], Version = 2, DestHost='192.168.0.1', Community='public'))
return res

print res 给我返回那个列表:

[('18',), ('13',), ('1',), ('2',), ('1',)]

OID 返回的所有值都是整数

问题:

我怎样才能得到一个里面只有整数的列表,像这样:

[18, 13, 1, 2, 1]

有人知道如何解决我的问题吗?

【问题讨论】:

  • 显然,没人知道怎么做。 :)

标签: python snmp net-snmp


【解决方案1】:
res = [('18',), ('13',), ('1',), ('2',), ('1',)]
res = [int(x[0]) for x in res] ## [18, 13, 1, 2, 1]

【讨论】:

  • 是的。学过的知识。我都计时了,列表理解更高效。 +1。
  • @idjaw 不确定时间,但它更符合 Python 风格,并且地图有些过时
  • 地图真的被弃用了吗?因为在 Python 3 中它实际上返回了一个生成器。所以看起来它仍然得到爱。但是,请查看:stackoverflow.com/a/5426851/1832539。 LC 英尺。
【解决方案2】:

您可以使用列表推导:

[int(x[0]) for x in res]

【讨论】:

    【解决方案3】:

    使用map

    a = [('18',), ('13',), ('1',), ('2',), ('1',)]
    
    print(map(lambda x: int(x[0]), a))
    

    输出:

    [18, 13, 1, 2, 1]
    
    • 编辑*

    虽然这可行,但列表推导的性能更高。看this答案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2013-01-15
      • 2019-01-26
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多