itertools.product
时间: 2023-08-29 22:13:42 浏览: 60
itertools.product is a Python module that provides a way to compute the Cartesian product of two or more iterables. It takes two or more iterables as input and returns an iterator that yields tuples containing one element from each of the input iterables.
For example, suppose we have two lists:
```
list1 = [1, 2, 3]
list2 = ['a', 'b']
```
We can use itertools.product to compute the Cartesian product of these two lists:
```
import itertools
cartesian_product = itertools.product(list1, list2)
for item in cartesian_product:
print(item)
```
This will output:
```
(1, 'a')
(1, 'b')
(2, 'a')
(2, 'b')
(3, 'a')
(3, 'b')
```
Note that the order of the input iterables matters. If we had used `itertools.product(list2, list1)` instead, the output would be:
```
('a', 1)
('a', 2)
('a', 3)
('b', 1)
('b', 2)
('b', 3)
```