Python 上的迭代算法(具有所需位置的排列)

iteration algoritm on Python (permutations with required position)

我有以下输入数据:

input_data = [
    ('obj1', 0),
    ('obj2', 0),
    ('obj3', 0),
    ('obj22', 0),
    ('obj4', 1),
    ('obj5', 1),
    ('obj6', 1),
    ('obj7', 2),
    ('obj8', 2),
    ('obj9', 3),
    ('obj10', 3),
] 

我需要编写一个算法来进行排列 乘以 2 但位置除外的项目(元组中的第二个元素) 对于左侧项目将 >= 右侧项目的位置或小于 1。

示例输出:

expected = [
    [('obj1', 0), ('obj4', 1)],
    [('obj1', 0), ('obj5', 1)],
    [('obj1', 0), ('obj6', 1)],

    [('obj2', 0), ('obj4', 1)],
    [('obj2', 0), ('obj5', 1)],
    [('obj2', 0), ('obj6', 1)],

    [('obj3', 0), ('obj4', 1)],
    [('obj3', 0), ('obj5', 1)],
    [('obj3', 0), ('obj6', 1)],

    [('obj22', 0), ('obj4', 1)],
    [('obj22', 0), ('obj5', 1)],
    [('obj22', 0), ('obj5', 1)],

    [('obj4', 1), ('obj7', 2)],
    [('obj4', 1), ('obj8', 2)],

    [('obj5', 1), ('obj7', 2)],
    [('obj5', 1), ('obj8', 2)],

    [('obj6', 1), ('obj7', 2)],
    [('obj6', 1), ('obj8', 2)],

    [('obj7', 2), ('obj9', 3)],
    [('obj7', 2), ('obj10', 3)],

    [('obj8', 2), ('obj9', 3)],
    [('obj8', 2), ('obj10', 3)],
]

如果我答对了你的问题,下面就是你的答案:

from itertools import permutations

input_data = [
    ('obj1', 0),
    ('obj2', 0),
    ('obj3', 0),
    ('obj22', 0),
    ('obj4', 1),
    ('obj5', 1),
    ('obj6', 1),
    ('obj7', 2),
    ('obj8', 2),
    ('obj9', 3),
    ('obj10', 3),
]

perm = permutations(input_data, 2)

expected = []
for p in perm:
    if p[0][1] < p[1][1]:
        expected.append([p[0], p[1]])

结果:

expected = [
[('obj1', 0), ('obj4', 1)]
[('obj1', 0), ('obj5', 1)]
[('obj1', 0), ('obj6', 1)]
[('obj1', 0), ('obj7', 2)]
[('obj1', 0), ('obj8', 2)]
[('obj1', 0), ('obj9', 3)]
[('obj1', 0), ('obj10', 3)]
[('obj2', 0), ('obj4', 1)]
[('obj2', 0), ('obj5', 1)]
[('obj2', 0), ('obj6', 1)]
[('obj2', 0), ('obj7', 2)]
[('obj2', 0), ('obj8', 2)]
[('obj2', 0), ('obj9', 3)]
[('obj2', 0), ('obj10', 3)]
[('obj3', 0), ('obj4', 1)]
[('obj3', 0), ('obj5', 1)]
[('obj3', 0), ('obj6', 1)]
[('obj3', 0), ('obj7', 2)]
[('obj3', 0), ('obj8', 2)]
[('obj3', 0), ('obj9', 3)]
[('obj3', 0), ('obj10', 3)]
[('obj22', 0), ('obj4', 1)]
[('obj22', 0), ('obj5', 1)]
[('obj22', 0), ('obj6', 1)]
[('obj22', 0), ('obj7', 2)]
[('obj22', 0), ('obj8', 2)]
[('obj22', 0), ('obj9', 3)]
[('obj22', 0), ('obj10', 3)]
[('obj4', 1), ('obj7', 2)]
[('obj4', 1), ('obj8', 2)]
[('obj4', 1), ('obj9', 3)]
[('obj4', 1), ('obj10', 3)]
[('obj5', 1), ('obj7', 2)]
[('obj5', 1), ('obj8', 2)]
[('obj5', 1), ('obj9', 3)]
[('obj5', 1), ('obj10', 3)]
[('obj6', 1), ('obj7', 2)]
[('obj6', 1), ('obj8', 2)]
[('obj6', 1), ('obj9', 3)]
[('obj6', 1), ('obj10', 3)]
[('obj7', 2), ('obj9', 3)]
[('obj7', 2), ('obj10', 3)]
[('obj8', 2), ('obj9', 3)]
[('obj8', 2), ('obj10', 3)]
]