如何找出字典中列表值的两两共同特征并存储到新字典
实现字典中列表的两两交集比较并存储结果
下面是实现两两列表比较、计算交集并存储到新字典的代码:
import itertools dic = {"df1":[1,2,3,4,5,555],"df2":[2,3,4,5,6,6,77,8,9,555],"df3":[1,2,2,3,4,5,6,76,7,555,5,4,3,2]} # 生成所有两两不重复的键组合 key_pairs = itertools.combinations(dic.keys(), 2) # 初始化存储结果的字典 pairwise_common = {} for key1, key2 in key_pairs: # 计算两个列表的交集(转成集合处理,自动去重) common_elements = set(dic[key1]) & set(dic[key2]) # 生成直观的结果键名 result_key = f"{key1}_intersect_{key2}" pairwise_common[result_key] = list(common_elements) print(pairwise_common)
代码解释:
- 使用
itertools.combinations(dic.keys(), 2)生成所有不重复的两两键组合,避免重复比较(比如不会同时出现(df1,df2)和(df2,df1)) - 遍历每一组键对,将对应的列表转为集合后用
&操作求交集,集合会自动处理重复元素 - 用f-string生成清晰的键名,格式为
[键1]_intersect_[键2],能直观体现是哪两个列表的交集 - 最后将交集结果转回列表(如果需要保留集合格式可以去掉
list()),存入结果字典
运行后输出的结果字典为:
{ 'df1_intersect_df2': [2, 3, 4, 5, 555], 'df1_intersect_df3': [1, 2, 3, 4, 5, 555], 'df2_intersect_df3': [2, 3, 4, 5, 555, 6] }
如果需要保留元素的出现次数(而非仅去重的交集),可以用collections.Counter实现:
from collections import Counter import itertools dic = {"df1":[1,2,3,4,5,555],"df2":[2,3,4,5,6,6,77,8,9,555],"df3":[1,2,2,3,4,5,6,76,7,555,5,4,3,2]} pairwise_common = {} for key1, key2 in itertools.combinations(dic.keys(), 2): cnt1 = Counter(dic[key1]) cnt2 = Counter(dic[key2]) # 计算带出现次数的交集 common_cnt = cnt1 & cnt2 # 将计数展开为列表 common_elements = [] for num, count in common_cnt.items(): common_elements.extend([num]*count) result_key = f"{key1}_intersect_{key2}" pairwise_common[result_key] = common_elements print(pairwise_common)
这个版本会保留元素的重复次数,比如df2里的6出现2次,df3里的6出现1次,交集里的6就会保留1次。
内容的提问来源于stack exchange,提问作者ella
相关产品推荐
相关产品推荐

