我想创建一个笛卡尔乘积,并从第二个和第三个位置选择相等或仅相差1的元组

import itertools

a = [(1,4), (2,2), (3,9),(7,4),(5,4)];

a1 = ( list(itertools.product(*a)))

print (a1)
i=a1[1]
k=a1[2]


new_list = list(filter(lambda i,k: (i-k <= 1) , a1))
print (my_list)


但是结果是

[(1, 2, 3, 7, 5), (1, 2, 3, 7, 4), (1, 2, 3, 4, 5), (1, 2, 3, 4, 4), (1, 2, 9, 7, 5), (1, 2, 9, 7, 4), (1, 2, 9, 4, 5), (1, 2, 9, 4, 4), (1, 2, 3, 7, 5), (1, 2, 3, 7, 4), (1, 2, 3, 4, 5), (1, 2, 3, 4, 4), (1, 2, 9, 7, 5), (1, 2, 9, 7, 4), (1, 2, 9, 4, 5), (1, 2, 9, 4, 4), (4, 2, 3, 7, 5), (4, 2, 3, 7, 4), (4, 2, 3, 4, 5), (4, 2, 3, 4, 4), (4, 2, 9, 7, 5), (4, 2, 9, 7, 4), (4, 2, 9, 4, 5), (4, 2, 9, 4, 4), (4, 2, 3, 7, 5), (4, 2, 3, 7, 4), (4, 2, 3, 4, 5), (4, 2, 3, 4, 4), (4, 2, 9, 7, 5), (4, 2, 9, 7, 4), (4, 2, 9, 4, 5), (4, 2, 9, 4, 4)]


    new_list = list(filter(lambda i,k: (i-k <= 1) , a1))
TypeError: <lambda>() missing 1 required positional argument: 'k'


我的lambda有什么问题?

最佳答案

import itertools
a =[(1,4),(2,2),(3,9),(7,4),(5,4)]
b = itertools.product(*a)
c = filter(lambda x: abs(x[1]-x[2])<=1, b)
print(c)


提供(为可见度进行编辑)

[(1, 2, 3, 7, 5),
 (1, 2, 3, 7, 4),
 (1, 2, 3, 4, 5),
 (1, 2, 3, 4, 4),
 (1, 2, 3, 7, 5),
 (1, 2, 3, 7, 4),
 (1, 2, 3, 4, 5),
 (1, 2, 3, 4, 4),
 (4, 2, 3, 7, 5),
 (4, 2, 3, 7, 4),
 (4, 2, 3, 4, 5),
 (4, 2, 3, 4, 4),
 (4, 2, 3, 7, 5),
 (4, 2, 3, 7, 4),
 (4, 2, 3, 4, 5),
 (4, 2, 3, 4, 4)]

关于python - 具有Itertools的Lambda无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44962076/

10-10 18:35