我试图找到一种有效的方法来处理这个问题。我有一个包含超过 40 万个条目的字典列表。我需要首先找到共享一个公共密钥的所有条目,假设从该列表中找到“pallet-id”,然后从该子列表中验证所有这些条目是否共享相同的“位置”密钥。我只对从初始列表中获取具有类似“pallet-id”的条目感兴趣,但前提是其中一个条目与其他条目的“位置”不同。
前任。
这将适用于托盘 ID 123456
entry1 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry2 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry3 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry4 = {'location': 'LOC1', 'pallet-id': '123456', ...}
由于所有共享相同的位置,我不在乎这一点。
这将适用于托盘 ID 5555
entry1 = {'location': 'LOC1', 'pallet-id': '5555', ...}
entry2 = {'location': 'LOC1', 'pallet-id': '5555', ...}
entry3 = {'location': 'LOC2', 'pallet-id': '5555', ...}
entry4 = {'location': 'LOC1', 'pallet-id': '5555', ...}
在这种情况下,由于一个位置不同,我想存储这 4 个条目。
我遇到的问题是,通过检查每个托盘 id 然后在初始列表中查找相同托盘 id 的其余部分,报告花费了无限量的时间,是否有更有效的方法来处理这个问题?
嵌套循环在这里是一个坏主意,因为它会导致二次时间复杂度。不过,您可以在线性时间内完成:
from collections import Counter
from operator import itemgetter
pal = itemgetter('pallet-id')
pal_loc = itemgetter('pallet-id', 'location')
# unique pallet-id, location combos
pallocs = set(map(pal_loc, entries))
# set([('5555', 'LOC1'), ('5555', 'LOC2'), ('123456', 'LOC1')])
# count pallet-id occurrences in the unique combos
count = Counter(pl[0] for pl in pallocs)
# Counter({'5555': 2, '123456': 1})
# filter the entries for pallet-ids with counts greater than 1
filtered_entries = [e for e in entries if count[pal(e)] > 1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句