请教一个Python的编程实现

有两个等长列表比如[a,b,c,d,e,f,g]和[1,2,3,4,5,6,7]现在要从两个列表各取一个元素两两一组匹配,每一个元素只能使用一次,直到用尽列表。在一定限制条件下,比如a不能匹配1457,b不能匹配234,c不能匹配23456,等等,输出所有可能的组合结果

使用内置排列组合函数吧,思路就是把其中一个列表进行全排列,总共有 7! = 5040个组合,然后依次判断另一个列表对应位置的限制,把剩下的排列与另一个列表用zip合并起来。

lst1 = ['a','b','c','d','e','f','g']
lst2 = [1,2,3,4,5,6,7]

from itertools import permutations

res = []
for i in permutations(lst2):
    if i[0] in [1,4,5,7] or i[1] in [2,3,4] or i[2] in [2,3,4,5,6]:
        continue
    res.append(list(zip(lst1,i)))

print(len(res))

总共可以得到384种组合方式

a = ['a','b','c','d','e','f','g']
b = [1,2,3,4,5,6,7]
c = []
for i in a:
    for j in b:
        t = str(j)
        if i=='a' and t in '1457':continue
        if i=='b' and t in '234':continue
        if i=='c' and t in '23456':continue
        c.append(i+t)

print(c)

#输出结果: ['a2', 'a3', 'a6', 'b1', 'b5', 'b6', 'b7', 'c1', 'c7', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7']