【问题标题】:List all combinations between two lists where element of first list is smaller than the element of the second list [duplicate]列出两个列表之间的所有组合,其中第一个列表的元素小于第二个列表的元素[重复]
【发布时间】:2019-06-12 18:34:52
【问题描述】:

我正在使用 python 3 和 itertools 在两个列表之间创建所有可能的组合。但是我需要添加一个约束,其中每对的第一个元素需要小于第二个元素。

例如:

list1=['A1','A2','C1']
list2=['A1','B1','B2']
result = list(itertools.product(list1, list2))

返回

[("A1", "A1"), ("A1", "B1"), ("A1", "B2"), ("A2", "A1"), ("A2", "B1"), ("A2", "B2"), ("C1", "A1"), ("C1", "B1"), ("C1", "B2")]

此时我想排除所有list1首字母大于list2首字母的元素。在这种情况下,结果中的最后三个元素将被排除,因为 C 大于 A,B。

所以最终结果等于

[("A1", "A1"), ("A1", "B1"), ("A1", "B2"), ("A2", "A1"), ("A2", "B1"), ("A2", "B2")]

【问题讨论】:

  • 为什么在完成所有组合后不应用过滤器?
  • list((x,y) for x, y in itertools.product(list1, list2) if x[0] <= y[0])?
  • 另外,您的结果中不能包含 ("A1", "A1"),因为 A1 = A1 但您说的第一个元素少于第二个元素,或者您的条件在问题中不正确?

标签: python python-3.x list combinations permutation


【解决方案1】:

为什么不在生成元素后过滤掉它们。本质上,创建产品迭代器并只选择元素(x,y) where x < y

result = [(x,y) for x, y in itertools.product(list1, list2) if x < y]

输出将是

[('A1', 'B1'), ('A1', 'B2'), ('A2', 'B1'), ('A2', 'B2')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多