基于公共元素将列表转换为集合的Python程序
给定一个列表列表,任务是编写一个Python程序,该程序可以将每个子列表转换为一个集合,如果子列表具有公共元素,则将它们组合成一个集合。打印的输出将是一个集合列表。
Input : test_list = [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 12]]
Output : [{11, 12, 13, 14, 15, 18, 19}, {1, 2, 3, 4, 5, 9}]
Explanation : List 1 and list 4 had 12 in common, hence all got merged to one.
Input : test_list = [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 22]]
Output : [{18, 12, 14, 15}, {1, 2, 3, 4, 5, 9}, {11, 19, 13, 22}]
Explanation : List 2 and list 3 had 1, 2 in common, hence all got merged to one.
方法:使用递归和union()
在这种情况下,我们根据条件执行使用 union() 获取所有具有相似元素的容器的任务。递归用于执行与大多数所需列表类似的任务。
例子:
Python3
# utility function
def common_set(test_set):
for idx, val in enumerate(test_set):
for j, k in enumerate(test_set[idx + 1:], idx + 1):
# getting union by conditions
if val & k:
test_set[idx] = val.union(test_set.pop(j))
return common_set(test_set)
return test_set
# utility function
# initializing lists
test_list = [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 12]]
# printing original list
print("The original list is : " + str(test_list))
test_set = list(map(set, test_list))
# calling recursive function
res = common_set(test_set)
# printing result
print("Common element groups : " + str(res))
输出:
The original list is : [[15, 14, 12, 18], [9, 5, 2, 1], [4, 3, 2, 1], [19, 11, 13, 12]]
Common element groups : [{11, 12, 13, 14, 15, 18, 19}, {1, 2, 3, 4, 5, 9}]