How does Python get Cartesian products from a list
This article is about how Python gets the Cartesian product from the list. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. You can use itertools.product in the standard library to get Cartesian product.
From itertools import product somelists = [[1,2,3], ['await,' b'], [4,5]] result = list (product (* somelists)) print (result)
2. Iterative method.
Def cartesian_iterative (pools): result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] return result
3. Recursive method.
Def cartesian_recursive (pools): if len (pools) > 2: pools [0] = product (pools [0], pools [1]) del pools [1] return cartesian_recursive (pools) else: pools [0] = product (pools [0], pools [1]) del pools [1] return poolsdef product (x, y): return [xx + [yy] if isinstance (xx, list) else [xx] + [yy] for xx in x for yy in y]
4. Lambda method.
Def cartesian_reduct (pools): return reduce (lambda XMagery y: product (XMagne y), pools) Thank you for reading! This is the end of the article on "how Python gets Cartesian products from the list". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!