我里面有一个巨大的字典列表,就像这样,其中每个字典有 4 个键。
l = [dict1 , dict2, dict3, dict4 .......]
dict1 = {'text': 'XYZ', 'x': 961, 'y': 420.59375, 'width': 141, 'height': 30}
dict2 = {'text': 'ABC', 'x': 962, 'y': 13.09375, 'width': 50, 'height': 33}
dict3 = {'text': 'XYZ', 'x': 961, 'y': 420.59375, 'width': 141, 'height': 30}
dict4 = {'text': 'ABC', 'x': 962, 'y': 13.09375, 'width': 50, 'height': 33}
我想找到 dict['x']
相同的列表的所有索引。
我想到的首字母缩写方法是 O(n^2) 方法,其中我将迭代每个索引并与每个其他索引进行比较。
请帮助我采取任何有效的方法(如果有)
预期输出:
{0,2} 因为 dict1 和 dict3 具有相同的 x
{1,3} 因为 dict2 和 dict4 具有相同的 x
最佳答案
您可以使用defaultdict
和一个 for 循环使其O(n)
:
l = [dict1 , dict2, dict3, dict4.......]
indexes = defaultdict(list)
for i, d in enumerate(l):
indexes[d["x"]].append(i)
关于python - 在字典列表中查找重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55864192/