gpt4 book ai didi

python - 查找列表的笛卡尔积,根据条件过滤掉元素

转载 作者:行者123 更新时间:2023-11-28 21:00:12 26 4
gpt4 key购买 nike

我最近遇到了这个表示法

a = [1,2,3,4]
b = [2,4,6]

c = [(x,y,z) for x in a for y in b for z in a]

首先我不知道如何在创建c时搜索符号,这种结构有名称吗?

此外,我相信 c 可以更新为不允许 x 等于 z。你能帮我解决这个问题吗?

我尝试过各种方法

c = [(x,y,z) for x in a for y in b for z in a for x != z]

但到目前为止我找不到任何有用的东西,甚至找不到有效的语法。

我想要完成的是找到 (a,b,a) 的每个组合,其中 a 只能在每一行中使用一次,因此结果会是

[(1, 2, 2),
(1, 2, 3),
(1, 2, 4),
(1, 4, 2),
(1, 4, 3),
(1, 4, 4),
(1, 6, 2),
(1, 6, 3),
(1, 6, 4),
(2, 2, 1),
(2, 2, 3),
(2, 2, 4),
(2, 4, 1),
(2, 4, 3),
(2, 4, 4),
(2, 6, 1),
(2, 6, 3),
(2, 6, 4),
(3, 2, 1),
(3, 2, 2),
(3, 2, 4),
(3, 4, 1),
(3, 4, 2),
(3, 4, 4),
(3, 6, 1),
(3, 6, 2),
(3, 6, 4),
(4, 2, 1),
(4, 2, 2),
(4, 2, 3),
(4, 4, 1),
(4, 4, 2),
(4, 4, 3),
(4, 6, 1),
(4, 6, 2),
(4, 6, 3)]

谢谢

最佳答案

它被称为列表理解,您可以在其中使用逻辑if 来过滤返回列表中的结果:

>>> a = [1,2,3,4]
>>> b = [2,4,6]
# if condition to skip results where `x` equals `z` v
>>> c = [(x,y,z) for x in a for y in b for z in a if x != z]
>>> c
[(1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 6, 2), (1, 6, 3), (1, 6, 4), (2, 2, 1), (2, 2, 3), (2, 2, 4), (2, 4, 1), (2, 4, 3), (2, 4, 4), (2, 6, 1), (2, 6, 3), (2, 6, 4), (3, 2, 1), (3, 2, 2), (3, 2, 4), (3, 4, 1), (3, 4, 2), (3, 4, 4), (3, 6, 1), (3, 6, 2), (3, 6, 4), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 6, 1), (4, 6, 2), (4, 6, 3)]

不使用嵌套列表理解,您可以使用 itertools.product 获得相同的行为。还有:

>>> from itertools import product

>>> [(x,y,z) for x, y, z in product(a, b, a) if x !=z]
[(1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 4, 2), (1, 4, 3), (1, 4, 4), (1, 6, 2), (1, 6, 3), (1, 6, 4), (2, 2, 1), (2, 2, 3), (2, 2, 4), (2, 4, 1), (2, 4, 3), (2, 4, 4), (2, 6, 1), (2, 6, 3), (2, 6, 4), (3, 2, 1), (3, 2, 2), (3, 2, 4), (3, 4, 1), (3, 4, 2), (3, 4, 4), (3, 6, 1), (3, 6, 2), (3, 6, 4), (4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 4, 1), (4, 4, 2), (4, 4, 3), (4, 6, 1), (4, 6, 2), (4, 6, 3)]

关于python - 查找列表的笛卡尔积,根据条件过滤掉元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791751/

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