是否有一个python内置程序可以使用“Is”比较从列表中提取不可损坏对象的“set”?

2024-05-16 04:10:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试提取列表中所有词典的集合,以便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?你知道吗


Tags: infalse列表forif字典isall
2条回答

如果要比较标识,则存储每个字典的^{} 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()那样)。你知道吗

对于相等性,键值对序列是可散列的(如果所有值都是可散列的);其中的^{}将用作测试内容唯一性的键:

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()

如果秩序不重要。你知道吗

因为您关心的是标识而不是值,所以您需要一个标识集。没有内置的身份集(或身份dict),部分原因是很容易自己构建一个性能合理的身份集:

dictlist = [.....]
iddict = {}
for d in dictlist:
     if id(d) not in iddict:
          iddict[id(d)] = d

你想要的是iddict.values()。它不保持dictlist的顺序,但是既然你要求一个set的类似物,我想这是没有问题的。你知道吗

相关问题 更多 >