【问题标题】:make all possible pairs from different list in python从python中的不同列表中生成所有可能的对
【发布时间】:2017-02-24 04:08:11
【问题描述】:

我用这种方式进行所有组合:

import itertools

lst = [[1, 2, 3], [1,2,2,4]]
combs = []

for i in xrange(1, len(lst)+1):
    combs.append(i)
    els = [list(x) for x in itertools.combinations(lst, i)]
    combs.append(els)

但我想要的是每个列表都包含里面所有可能的元素组合。使用上面的解决方案,每个元素对都是分散的。我该如何解决?

【问题讨论】:

  • 提供示例输入输出,以便我们了解您的需求!
  • 不清楚你想要什么。举一个期望输出的例子。
  • 你能分享你的结果和想要的输出吗?
  • 我想要的输出是这样的,[[(1,2),(1,3),(1,2,3)],[(1,2),(1,4) ,(2,2),(2,4)]]
  • 对是什么意思? (1,2,3) 是一对数字吗?

标签: python list combinations


【解决方案1】:

你在寻找这样的东西吗?

import itertools

lst = [1, 2, 3], [1, 2, 2, 4]
combs = []

for i in range(len(lst)):
    els = [list(x) for x in itertools.combinations(lst[i], 2)]
    combs.append(els)

print(combs)

输出

[[[1, 2], [1, 3], [2, 3]], [[1, 2], [1, 2], [1, 4], [2, 2], [2, 4], [2, 4]]]

既然你说,你想要-each element in its own list make pairs and put back in that list,所以我假设[1, 2, 3] 应该转换为[[1, 2], [1, 3], [2, 3]]。上面的例子做同样的事情!


更新

如果您想从这些列表中生成所有可能的组合(长度大于 1),那么您可以执行以下操作。

import itertools

lst = [1, 2, 3], [1, 2, 2, 4]
combs = []

for i in range(len(lst)):
    temp_list = []
    for j in range(len(lst[i])+1):
        if j < 2: # skipping zero and one length combinations
            continue
        els = [x for x in itertools.combinations(lst[i], j)]
        temp_list.extend(els)

    # remove duplicate combinations
    new_list = []
    [new_list.append(i) for i in temp_list if not new_list.count(i)]
    combs.append(new_list)

print(combs)

输出

[[(1, 2), (1, 3), (2, 3), (1, 2, 3)], [(1, 2), (1, 4), (2, 2), (2, 4), 
  (1, 2, 2), (1, 2, 4), (2, 2, 4), (1, 2, 2, 4)]]

【讨论】:

  • 但我不想指定对数。我想要这些组合中的所有可能性。
猜你喜欢
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 2012-08-14
  • 1970-01-01
  • 2017-10-13
相关资源
最近更新 更多