Cartesian product of two or more lists: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Replaced original with a function wrapper around itertools.product)
Line 2,047:
Using itertools:
<lang python>import itertools
lists_1 = [[1,2],[3,4]]
lists_2 = [[3,4],[1,2]]
for element in itertools.product(*lists_1):
print(element)
print()
for element in itertools.product(*lists_2):
print(element)</lang>
Output:
<pre>
(1, 3)
(1, 4)
(2, 3)
(2, 4)
 
def cp(lsts):
(3, 1)
for element in return list(itertools.product(*lists_1lsts)):
(3, 2)
 
(4, 1)
if __name__ == '__main__':
(4, 2)
from pprint import pprint as pp
for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),
((1, 2, 3), (30,), (500, 100)),
((1, 2, 3), (), (500, 100))]:
print(elementlists, '=>')
pp(cp(lists), indent=2)
</lang>
{{out}}
lists_1 = <pre>[[1, 2], [3, 4]] =>
[(1, 3), (1, 4), (2, 3), (2, 4)]
lists_2 = [[3, 4], [1, 2]] =>
[(3, 1), (3, 2), (4, 1), (4, 2)]
[[], [1, 2]] =>
[]
[[1, 2], []] =>
[]
((1776, 1789), (7, 12), (4, 14, 23), (0, 1)) =>
[ (1776, 7, 4, 0),
(1776, 7, 4, 1),
(1776, 7, 14, 0),
(1776, 7, 14, 1),
(1776, 7, 23, 0),
(1776, 7, 23, 1),
(1776, 12, 4, 0),
(1776, 12, 4, 1),
(1776, 12, 14, 0),
(1776, 12, 14, 1),
(1776, 12, 23, 0),
(1776, 12, 23, 1),
(1789, 7, 4, 0),
(1789, 7, 4, 1),
(1789, 7, 14, 0),
(1789, 7, 14, 1),
(1789, 7, 23, 0),
(1789, 7, 23, 1),
(1789, 12, 4, 0),
(1789, 12, 4, 1),
(1789, 12, 14, 0),
(1789, 12, 14, 1),
(1789, 12, 23, 0),
(1789, 12, 23, 1)]
((1, 2, 3), (30,), (500, 100)) =>
[ (1, 30, 500),
(1, 30, 100),
(2, 30, 500),
(2, 30, 100),
(3, 30, 500),
(3, 30, 100)]
((1, 2, 3), (), (500, 100)) =>
[]
</pre>