我有一个dicts列表(列表中每个条目都是dict)。每个dict都有一组不同的键,因此一个dict可能有一个与列表中其他dicts不同的键。我试图在此列表中找到特定的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
答案 0 :(得分:0)
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
答案 1 :(得分:0)
我不清楚,这可能会有所帮助:
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}]
希望这有帮助。