【问题标题】:Counting all possible combinations in a given list of list计算给定列表中所有可能的组合
【发布时间】:2023-03-17 17:28:01
【问题描述】:
我有一个列表列表为list_1 =[[A,B,C,D],[A,D],[B,C,D]]。我想要一个输出,例如:
因此,如上所示,我期望列表中存在的所有可能组合的计数。
【问题讨论】:
标签:
python
list
combinations
combinatorics
counting
【解决方案1】:
尝试使用它,它将遍历所有列表并使用 itertools.combinations 计算此列表中所有可能的组合并将数字添加到 result
import itertools
list_1 =[["A","B","C","D"],["A","D"],["B","C","D"]]
result = {}
for sublist in list_1:
for L in range(1, len(sublist)+1):
for subset in list(itertools.combinations(sublist, L)):
key = "".join(list(subset))
if key in result:
result[key] += 1
else:
result[key] = 1
如果你想打印它们:
for item in result:
print(item + " => " + str(result[item]))
# Output:
# A => 2
# B => 2
# C => 2
# D => 3
# AB => 1
# AC => 1
# AD => 2
# BC => 2
# BD => 2
# CD => 2
# ABC => 1
# ABD => 1
# ACD => 1
# BCD => 2
# ABCD => 1