gpt4 book ai didi

python - 带有 itertools 的 Lambda 不工作

转载 作者:行者123 更新时间:2023-11-30 22:34:04 25 4
gpt4 key购买 nike

我想创建一个笛卡尔积,并从第二个和第三个位置选择相等或仅相差 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com