【发布时间】: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_field 和 some_other_field 是如何不同的,以及不同的常量:A_CONSTANT_I_HAVE_DEFINED, ANOTHER_CONSTANT, SOME_OTHER_CONSTANT。请注意,some_field 可能不在列表中的每个项目中,some_other_field 也是如此
【问题讨论】:
标签: python list dictionary