【问题标题】:Using python itertools to find all possible combinations of sublist elements that sums to target values使用 python itertools 查找总和为目标值的子列表元素的所有可能组合
【发布时间】:2020-08-25 13:59:17
【问题描述】:

拜托,我已经完成了已回答的问题,但找不到答案。我对 python 还很陌生。

我的问题是:

例如,假设:

我的列表 = [[2,4], [1,3], [3,5], [1,4]]

如何使用 python itertools/combinations 遍历嵌套列表 (myList),以便找到 myList 元素的所有可能组合(即子列表),其零索引(即 myList[i][0])和第一索引(即 myList[i][1]) 的总和分别为 4 和 11(其中 i 在 (len(myList)) 范围内)。

myList我想找到满足以下两个条件的子列表的所有可能组合:

sum(myList[i][0]) == 4 和 sum(myList[i][1]) == 11(其中 i 在范围内 (len(myList))

所以,从 myList 我想得到输出为:

输出:[[[2,4]、[1,3]、[1,4]]、[任何其他组合_1]、[任何其他组合_2]、[等等]]

请,如果您能提供任何帮助,我将不胜感激。谢谢。

【问题讨论】:

  • 所以您想要获取myList 元素的任意子集 - 可以有任意数量的元素,从 0 到全部?
  • @Karl Knechtel 好的,谢谢
  • 请正确格式化代码,click here to learn how.

标签: python loops iteration combinations itertools


【解决方案1】:

这应该可行:

from itertools import combinations

myList = [[2,4], [1,3], [3,5], [1,4]]

combos = [
    x for i in range(1, len(myList)+1)
    for x in combinations(myList, i)
    if sum(list(zip(*x))[0]) == 4 and sum(list(zip(*x))[1]) == 11
]

【讨论】:

  • 没问题。棘手的部分是让zip 部分中的所有括号都正确。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多