示例:
complete_dict = dict()
common_set = set()
for count, group_name in enumerate(groups_dict):
complete_dict[group_name] = dict() # grabs a json file = group_name.json
if count > 0:
common_set.intersection_update(complete_dict[group_name])
else:
# this accounts for the fact common_set is EMPTY to begin with
common_set.update(complete_dict[group_name])
WHERE:dict2
包含k:v成员(组):int(x)
是否有更合适的方法来处理交叉点的初始状态?
即。我们无法将第一个complete_dict[group_name]
与common_set
相交,因为它为空,因此结果也为空。
答案 0 :(得分:2)
避免特殊情况的一种方法是使用项目的内容初始化集合。由于与自身相交的值是值本身,因此您不会以任何方式丢失任何内容。
这是尝试展示这是如何工作的。我不确定我是否理解了您的不同dict(...)
调用应该代表的内容,因此这可能无法完美地转换为您的代码,但它应该让您走上正确的道路。
it = iter(dict(...)) # this is the dict(...) from the for statement
first_key = next(it)
results[first_key] = dict(...) # this is the dict(...) from inside the loop
common = set(results[first_key]) # initialize the set with the first item
for key in it:
results[key] = dict(...) # the inner dict(...) again
common.intersection_update(result[key])
正如jamylak评论的那样,你对各种词典的keys
方法所做的调用总是不必要的(如果你不进行任何索引或者字典,那么字典的行为就像set
个键。使用特定于映射的方法)。我还给出了更符合Python风格的选择变量(lowercase
用于常规变量,CAPITALS
保留用于常量。)
答案 1 :(得分:1)
遵循Blcknght的答案,但复杂性和重复性较低:
common = None
uncommon = {}
for key in outer_dict:
inner = uncommon[key] = inner_dict(...)
if common is None:
common = set(inner)
else:
common.intersection_update(inner)
与Blcknght一样,很难知道这是否捕获了原文的意图,因为变量名称不是描述性的,也不是不同的。
答案 2 :(得分:0)
逻辑上,当我们想要分配几个集合之间的交集输出时,我们将最小集合(设置为最小长度)分配给输出集合并将其他集合与它进行比较吗?
uncommon_result = dict(...) # a method that returns a dict()
common_set=sorted([(len(x),x) for x in uncommon_result.values()])[0][1]
for a_set in uncommon_result.values():
common_set.intersection_update(a_set)
我知道第二行可能是启动COMMON_SET
最糟糕的事情之一,因为它做了很多不必要的工作,但数学上几乎所有时候我们都想知道哪一个是最小的,在这种情况下,这些作品并非徒劳。
编辑:如果uncommon_result是一个dicts的词典,你可能需要添加另一个for循环来检查它的键,并且在上面的内部有一些小的改动,你会再次好起来。