【问题标题】:List of dicts each with different keys, best way to look for a sequence of dicts每个具有不同键的字典列表,查找字典序列的最佳方法
【发布时间】:2016-09-29 03:33:22
【问题描述】:

我有一个字典列表(每个条目都是字典的列表)。每个 dict 都有一组不同的键,因此一个 dict 可能具有列表中其他 dict 不存在的键。我正在尝试在此列表中找到特定的 dicts 顺序。基本上,该列表来自wireshark 捕获,我想查找某些数据包。列表中间有一个特定的数据包序列。此外,在这个序列中,有一些我希望忽略/过滤的数据包。实现这一目标的最佳方法是什么?我在下面写了一些伪代码:

for i in range(len(packets)):
    p = packets[i].fields # This method turns the packet object into a dict
    try:
        if p['some_field'] == A_CONSTANT_I_HAVE_DEFINED:
            # Mark this packet as part of the sequence
            # Save as part of sequence
            first_packet = p
            # Do not check for this condition again! I want to go to the next
            # iteration once I come across a packet with similar property
            # (the equality satisfied)
        if p['some_field'] == ANOTHER_CONSTANT:
            # Same as above
            second_packet = p
        if p['some_other_field'] == SOME_OTHER_CONSTANT:
            # Same as above
            third_packet = p
     except KeyError as err:
         pass

# Now I should have first_packet, second_packet and third_packet
# The list packets will always have the sequence of packets I am looking for

请注意我的字段 some_fieldsome_other_field 是如何不同的,以及不同的常量:A_CONSTANT_I_HAVE_DEFINED, ANOTHER_CONSTANT, SOME_OTHER_CONSTANT。请注意,some_field 可能不在列表中的每个项目中,some_other_field 也是如此

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    我不清楚,这可能会有所帮助:

    a = [{'a': 1}, {'a':1, 'b':1}, {'c':1}]
    filtered_list = filter(lambda x: x.get('a') or x.get('b'), a)
    # OP [{'a': 1}, {'a': 1, 'b': 1}]
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:
      first_packet = None
      second_packet = None
      third_packet = None
      packets_found =  0
      
      for packet in packets:
          val = packet.get('some_field', None)
          if (val == A_CONSTANT_I_HAVE_DEFINED) and (first_packet is not None):
              first_packet = packet
              packets_found += 1
          elif (val == ANOTHER_CONSTANT) and (second_packet is not None):
              second_packet = packet
              packets_found += 1
          elif (packet.get('some_other_field', None) == SOME_OTHER_CONSTANT) and (third_packet is not None):
              third_packet = packet
              packets_found += 1
      
          if packets_found == 3:
              break
      

      【讨论】:

      • 一旦条件满足,我想停止尝试,即一旦我在序列中找到了一个数据包,那么它不应该再次进行比较。
      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多