[英]compute Cartesian product of 2 sets, Is it possible to force the order of elements in a set?
I am trying to print this set with Python我正在尝试用 Python 打印这个集合
Cartesian_product = []
A = ['x', 'y', 'z']
B = ['1', '2', '3']
[{b,a} for b in B for a in A]
no matter, {b,a}
or {a,b}
, for b in B for a in A
or for a in A for b in B
, the output will alway be无论是
{b,a}
还是{a,b}
, for b in B for a in A
或for a in A for b in B
,输出总是
[{'1', 'x'},
{'1', 'y'},
{'1', 'z'},
{'2', 'x'},
{'2', 'y'},
{'2', 'z'},
{'3', 'x'},
{'3', 'y'},
{'3', 'z'}]
is it possible to force the order of elements in this set as {'x', '1'}, {'x', '2'} ?是否可以将此集合中元素的顺序强制为 {'x', '1'}, {'x', '2'} ?
The product A × B
is the set of ordered pairs (a, b)
where a ∈ A
and b ∈ B
.乘积
A × B
是有序对(a, b)
a ∈ A
(a, b)
其中a ∈ A
和b ∈ B
。 This is not the same as the product B × A
, which is the set of ordered pairs (b, a)
.这与乘积
B × A
,后者是有序对(b, a)
的集合。 You can see this using the product
function from the itertools
module.您可以使用
itertools
模块中的product
函数看到这一点。
>>> A = ['x', 'y', 'z']
>>> B = ['1', '2', '3']
>>> list(product(A, B))
[('x', '1'), ('x', '2'), ('x', '3'), ('y', '1'), ('y', '2'), ('y', '3'), ('z', '1'), ('z', '2'), ('z', '3')]
>>> list(product(B, A))
[('1', 'x'), ('1', 'y'), ('1', 'z'), ('2', 'x'), ('2', 'y'), ('2', 'z'), ('3', 'x'), ('3', 'y'), ('3', 'z')]
So you must use tuples, not sets, to represent the elements of a Cartesian product.所以你必须使用元组而不是集合来表示笛卡尔积的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.