python - 从 dict 列表中删除具有相同 id 的 dict

标签 python python-3.x list dictionary nested

我想从字典列表中删除具有相同 ID 的字典。

def removeDuplicate(elems, id):
    new_list = []
    for elem in elems:
        if not elem[id] in [d[id] for d in new_list if id in d]:
            new_list.append(elem)
    return new_list


a = [
    {0 : 'a', 'id' : 2, 2 : 'c', time : '1'},
    {0 : 'a', 'id' : 2, 2 : 'c', time : '2'},
    {0 : 'a', 'id' : 3, 2 : 'c', time : '3'},
    {0 : 'a', 'id' : 4, 2 : 'c', time : '4'},
    {0 : 'a', 'id' : 5, 2 : 'c', time : '5'},
    {0 : 'a', 'id' : 4, 2 : 'c', time : '6'},
    {0 : 'a', 'id' : 2, 2 : 'c', time : '7'},
    {0 : 'a', 'id' : 3, 2 : 'c', time : '8'},
]
print(a)

a = removeDuplicate(a, 'id')

print(a)

它对 7000 个元素工作正常,但对 500 000 个元素需要很长时间。

是否有更好的方法来删除这些事件?

最佳答案

在进行查找时尝试使用 set,因为它的复杂度仅为 O(1)。也尽量不要在不需要时循环。

你的这个稍微修改过的代码应该足够快,即使对于 50 万个元素也是如此

def removeDuplicate(elems, id):
    new_list = []
    read_ids = set()
    for elem in elems:
        if elem[id] not in read_ids:
            read_ids.add(elem[id])
            new_list.append(elem)
    return new_list

关于python - 从 dict 列表中删除具有相同 id 的 dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58918713/

相关文章:

list - 在 Dart 中显示没有重复项的列表 <Map>

python - 下载 HTML 页面及其内容

python - 如何在 Pyramid 中的 SQLAlchemy 中的多个选择中维护多表完整性?

python - 使用自己的字母字符串解密密文时遇到问题(python)

r - 如何在不在 r 中输入名称的情况下列出许多数据框?

c# - IQueryable、ICollection、IList 和 IDictionary 接口(interface)之间的区别

python - 适用于 Python 的 Amazon Lex 模拟

python - 根据值更改操作长度

python-3.x - 使用整数的内存 View 索引 Cython 内存 View

python - 使用 filedialog 时 Tkinter 窗口和脚本卡住