Python 程序用于在集合列表中查找重复集合
pythonserver side programmingprogramming更新于 2025/11/9 10:52:17
当需要在集合列表中查找重复集合时,会使用‘Counter’和‘frozenset’。
示例
下面是相同的演示
from collections import Counter
my_list = [{4, 8, 6, 1}, {6, 4, 1, 8}, {1, 2, 6, 2}, {1, 4, 2}, {7, 8, 9}]
print("列表为:")
print(my_list)
my_freq = Counter(frozenset(sub) for sub in my_list)
my_result = []
for key, value in my_freq.items():
if value > 1 :
my_result.append(key)
print("结果为:")
print(my_result)
输出
列表为:
[{8, 1, 4, 6}, {8, 1, 4, 6}, {1, 2, 6}, {1, 2, 4}, {8, 9, 7}]
结果为:
[frozenset({8, 1, 4, 6})]
解释
定义一个集合值列表并显示在控制台上。
使用‘frozenset’和‘Counter’对其进行迭代。
这给出了列表中每个值的频率。
这被分配给一个变量。
创建一个空列表。
对变量的元素进行迭代,如果频率大于 1,则将其附加到空列表中。
这显示为控制台上的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

