【问题标题】:Find different combinations from two lists从两个列表中查找不同的组合
【发布时间】:2020-08-12 16:16:35
【问题描述】:

给定两个任意长度的列表,我想找到两个列表之间所有可能的组合,然后在新列表中添加该组合的字典对。

例如,这两个列表是:

List1 - ['A', 'B']

List2 - [1, 2]

结果列表应具有以下值:

[{'A':1, 'B':1}, {'A':1,'B':2}, {'A':2, 'B':1}, {'A':2, 'B':2}]

我找到的所有解决方案都只是给出了可能的组合。所以,假设我有一个长度为 3 和 2 的列表。可能的组合只有 6 个值。但是,根据我的要求,应该有 8 个值。

我使用的代码:

first_list = ['A', 'B', 'C'] 
second_list = [1, 2]
 
combinations = [(a,b) for a in first_list for b in second_list]

输出如下:

[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

虽然我想要的输出是:

[{'A':1, 'B':1, 'C':1},
 {'A':1, 'B':1, 'C':2},
 {'A':1, 'B':2, 'C':1},
 {'A':1, 'B':2, 'C':2},
 {'A':2, 'B':1, 'C':1},
 {'A':2, 'B':1, 'C':2},
 {'A':2, 'B':2, 'C':1},
 {'A':2, 'B':2, 'C':2}]

【问题讨论】:

  • 请用您尝试过的代码更新您的问题。
  • 这些不是组合,而是笛卡尔积的元素。因此,您可以使用itertools.product。另外——导致 8 个而不是 6 个“组合”的要求是模糊的。请澄清。为什么不使用 3 和 2 的预期输出示例?
  • 您已对其进行了编辑,但您未指定的要求导致在(3,2) 情况下预期输出 8 个元素而不是 6 个元素仍然是模糊的。您的示例的实际预期输出是什么?
  • 我也编辑了所需的输出。

标签: python list


【解决方案1】:

您可以使用itertools.product 来创建部分组合:

from itertools import product

first_list = ['A', 'B', 'C'] 
second_list = [1, 2]

out = product(second_list, repeat=len(first_list))

combinations = [{f:s for (f,s) in zip(first_list, c)} for c in out]

print(combinations)

根据需要输出。

【讨论】:

  • 我还将第二部分转换为嵌套列表理解。
  • 好的,谢谢。我也会做出这些改变。 (是的 en(..) 是一个错字)。
【解决方案2】:

你应该查一下here

你可以使用

list1 = ["a", "b", "c"]
list2 = [1, 2]
all_combinations = []

list1_permutations = itertools.permutations(list1, len(list2))
Get all permutations of `list1` with length 2

for each_permutation in list1_permutations:
    zipped = zip(each_permutation, list2)
    all_combinations.append(list(zipped))

print(all_combinations)

输出

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    相关资源
    最近更新 更多