【问题标题】: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]]。我想要一个输出,例如:

因此,如上所示,我期望列表中存在的所有可能组合的计数。

【问题讨论】:

  • 欢迎堆栈溢出。请edit 将您的预期输出包含在您的问题文本中,而不是作为图像,以制作minimal reproducible example。还请根据您自己的研究显示您迄今为止尝试过的内容,以及您的尝试出了什么问题。例如itertools、循环等

标签: 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多