简体   繁体   中英

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

在此处输入图片说明

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

[{'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'} ?

The product A × B is the set of ordered pairs (a, b) where a ∈ A and b ∈ B . This is not the same as the product B × A , which is the set of ordered pairs (b, a) . You can see this using the product function from the itertools module.

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM