【问题标题】:Get fixed size combinations of a list of lists in python?在python中获取列表列表的固定大小组合?
【发布时间】:2021-08-10 04:06:21
【问题描述】:

我正在寻找 itertools.product(*a) 的修改版本。此命令通过从每个列表中选择元素来返回组合,但我需要限制大小。

假设,

mylist = [[6, 7, 8], [3, 5, 9], [2, 1, 4]]

output: (6, 3), (6, 2),....(3, 2)... when size is 2

列表的数量和大小不固定。我需要一些足够动态的东西。

【问题讨论】:

  • [list(combinations(i,2)) for i in mylist]?
  • @Sujay 这个命令返回 [[(6, 7), (6, 8), (7, 8)], [(3, 5), (3, 9), (5 , 9)], [(2, 1), (2, 4), (1, 4)]] 即在列表中创建组合,而不是跨多个列表。
  • 检查我的答案?

标签: python list combinations slice itertools


【解决方案1】:

你可以试试:

from itertools import product, combinations, chain

mylist=[[6, 7, 8], [3, 5, 9], [2, 1]]
size = 2

results = chain.from_iterable(product(*t) for t in combinations(mylist, size))
print(list(results))

【讨论】:

  • 它有效,谢谢.. 但这里不是性能问题吗?
【解决方案2】:

也许你可以试试这个:

from itertools import chain, combinations
l=[[6, 7, 8], [3, 5, 9], [2, 1, 4]]
x=list(combinations(chain.from_iterable(l),2))
print(x)

【讨论】:

  • 仍然从每个列表中获取组合,即 (6,7),(6,8)...我们可以删除它们吗?
【解决方案3】:

解决方案:

import itertools

size = 2
mylist = [[6, 7, 8], [3, 5, 9], [2, 1, 4]]

res = []
for x in list(itertools.product(*mylist)):
    res += itertools.combinations(x, size)
print(set(res))

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 2017-10-31
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多