gpt4 book ai didi

python - 是否有 python 内置函数使用 'set' 比较从列表中提取不可散列对象的 'is'?

转载 作者:行者123 更新时间:2023-11-28 21:21:51 25 4
gpt4 key购买 nike

我正在尝试提取列表中所有词典的集合,使得 dict1 is dict2 == False 对于集合中的任何两个词典。不能使用 set() 将字典列表缩减为一个集合,因为它们不可散列。我意识到我可以做到以下几点:

dictlist = [.....]
setlist = []
for d in dictlist:
if all(s is not d for s in setlist):
setlist.append(d)

是否有类似于 set() 的 python 内置(使用 c,速度快得多)来减少列表,只是不需要 hashable?

最佳答案

如果你想比较identity 然后存储 id() function 的结果对于每个字典:

seen = set()
unique = [d for d in dictlist if id(d) not in seen and not seen.add(id(d))]

unique = {id(d): d for d in dictlist}.values()

这消除了基于对象标识的重复项,而不是基于内容的相等性。第一种形式维持秩序,第二种形式不维持秩序(就像 set() 那样)。

对于相等性,键值对序列可散列的(如果所有值都是可散列的);一个frozenset()这些将作为测试内容唯一性的关键:

seen = set()
hashable = lambda d: frozenset(d.items())
unique = [d for d in dictlist if hashable(d) not in seen and not seen.add(hashable(d))]

对于保序列表或:

unique = {frozenset(d.items()): d for d in dictlist}.values()

如果顺序不重要。

关于python - 是否有 python 内置函数使用 'set' 比较从列表中提取不可散列对象的 'is'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20593392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com