如何拆分带重复元素的集合
对于包含重复元素的集合,需要拆分成多个不带重复元素的小集合。以下是如何使用 python 来解决此问题:
datas = [29, 36, 37, 37, 39, 39, 955, 955, 955, 961, 961, 962, 962] elementcounts = {} maxcount = 0 for data in datas: if data in elementcounts: count = elementcounts[data] else: count = 0 elementcounts[data] = count + 1 if count + 1 > maxcount: maxcount = count + 1 sets = [] for i in range(maxcount): sets.append(set()) for key in elementcounts.keys(): count = elementcounts[key] for i in range(count): sets[i].add(key) print(sets)
此代码会创建多个集合,其中每个集合包含不重复的元素。在给定的示例中,将输出以下集合:
[set([29, 36, 37, 39, 955, 961, 962]), set([37, 39, 955, 961, 962]), set([955])]