[英]compute Cartesian product of 2 sets, Is it possible to force the order of elements in a set?
我正在嘗試用 Python 打印這個集合
Cartesian_product = []
A = ['x', 'y', 'z']
B = ['1', '2', '3']
[{b,a} for b in B for a in A]
無論是{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'}]
是否可以將此集合中元素的順序強制為 {'x', '1'}, {'x', '2'} ?
乘積A × B
是有序對(a, b)
a ∈ A
(a, b)
其中a ∈ A
和b ∈ B
。 這與乘積B × A
,后者是有序對(b, a)
的集合。 您可以使用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')]
所以你必須使用元組而不是集合來表示笛卡爾積的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.