Hello! 欢迎来到小浪资源网!


如何将包含重复元素的集合拆分成多个不重复元素的小集合?


如何将包含重复元素的集合拆分成多个不重复元素的小集合?

拆分重复元素集合

给定一个包含重复元素的集合,如何将其拆分成多个不带重复元素的小集合?

例如,对于集合 [29, 36, 37, 37, 39, 39, 955, 955, 955, 961, 961, 962, 962],可以拆分成三个小集合:

  • [29, 36, 37, 39, 955, 961, 962]
  • [37, 39, 955, 961, 962]
  • [955]

python 实现

以下 python 代码利用元素计数来拆分集合:

datas = [29, 36, 37, 37, 39, 39, 955, 955, 955, 961, 961, 962, 962] elementcounts = {}  maxcount = 0 for data in datas:     elementcounts[data] = elementcounts.get(data, 0) + 1     maxcount = max(maxcount, elementcounts[data])  sets = [set() for _ in range(maxcount)] for data, count in elementcounts.items():     for i in range(count):         sets[i].add(data)  print(sets)

输出结果:

[set([29, 36, 37, 39, 955, 961, 962]), set([37, 39, 955, 961, 962]), set([955])]

相关阅读