作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近遇到了这个表示法
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/
我是一名优秀的程序员,十分优秀!