【问题标题】:Accessing values of a dictionary in a list using lambda使用 lambda 访问列表中字典的值
【发布时间】:2016-05-28 15:08:59
【问题描述】:

我是 python 的新手。我在一个列表中有多个字典,我想根据值进行一些分析。我使用 lambda 的原因是因为函数并不总是预期的。我只是显示 2 个字典以供参考,但输出有时会给我多个字典。

statistics = [{"ip_dst": "10.0.0.1", "ip_proto": "icmp", "ip_src": "10.0.0.3",
               "bytes": 1380, "port_dst": 0, "packets": 30, "port_src": 0},
              {"ip_dst": "10.0.0.3", "ip_proto": "icmp", "ip_src": "10.0.0.1",
               "bytes": 1564, "port_dst": 0, "packets": 34, "port_src": 0}]

packets = filter(lambda x: x[0]["packets"], statistics)
ip_src = filter(lambda x: x[0]["ip_src"], statistics)
ip_proto = filter(lambda x: x[0]["ip_proto"], statistics)

当我使用print 语句时,它给了我一个关键错误:0。我知道数据包的值是一个整数,而对于 ip_src/ip_proto,该值是一个字符串。

如何使用 lambdas 访问这些值?

【问题讨论】:

    标签: python list dictionary lambda


    【解决方案1】:

    如果您尝试将数据包提取为单独的项目列表,则不会使用过滤器。过滤器只会减少新列表中的字典数量。您可以使用列表推导,

    packets = [x['packets'] for x in statistics]
    print(packets)
    # [30, 34]
    

    这会在统计中创建x['packets'] 值的列表。

    其他两组值相同。

    【讨论】:

      【解决方案2】:

      您不需要[0]

      使用filter(lambda x: ...) 时,x 是可迭代对象中的元素。 由于您有一个字典列表,x 将是字典本身。

      你的代码应该是:

      statistics = [{"ip_dst": "10.0.0.1", "ip_proto": "icmp", "ip_src": "10.0.0.3", "bytes": 1380, "port_dst": 0, "packets": 30, "port_src": 0}, {"ip_dst": "10.0.0.3", "ip_proto": "icmp", "ip_src": "10.0.0.1", "bytes": 1564, "port_dst": 0, "packets": 34, "port_src": 0}]
      
      
      packets = filter(lambda x: x["packets"], statistics)
      ip_src = filter(lambda x: x["ip_src"], statistics)
      ip_proto = filter(lambda x: x["ip_proto"], statistics)
      

      【讨论】:

      • 当我打印“打印数据包”时,而不是只给我数据包的值。输出是整个列表。 ip_src 和 ip_proto 相同。
      • 然后使用 Andy G 的答案。 filter 没有做你认为它做的事情:docs.python.org/2/library/functions.html#filter
      【解决方案3】:

      过滤器函数返回原始列表,其中不包含 lambda 计算结果为 false 的元素。所以,如果你正确地做到了,你无论如何都会得到所有的元素,因为在 Python 中,非空字符串或 0 以外的值被认为是 True。

      如果您只想获取键的这些值,则需要列表理解。

      packets = list(x["packets"] for x in statistics)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        相关资源
        最近更新 更多