python:itertools product

本文介绍了Python的itertools.product模块,重点讨论了如何使用它来替代嵌套for循环,包括确定和不确定重数的情况。通过实例1和实例2,展示了product的输出结果,强调其返回的是一个可迭代对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接口

Docstring:     
product(*iterables, repeat=1) --> product object

Cartesian product of input iterables.  Equivalent to nested for-loops.

For example, product(A, B) returns the same as:  ((x,y) for x in A for y in B).
The leftmost iterators are in the outermost for-loop, so the output tuples
cycle in a manner similar to an odometer (with the rightmost element changing
on every iteration).

To compute the product of an iterable with itself, specify the number
of repetitions with the optional repeat keyword argument. For example,
product(A, repeat=4) means the same as product(A, A, A, A).

product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)
product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...

使用场景

  • 对确定的n重嵌套for循环,可以用itertools.product进行替代。
  • 对n重for循环,n不确定,为一个可变的参数。则此时只能用itertools.product来有效表达。

实例1

from itertools import product

a = ['A','B','C']
b = range(2)
res1 = []
# 方法1:for循环
for i in a:
    for j in b:
        res1.append((i,j))
print(res1)

# 方法2:itertools.product
res2 = product(a, b)
print(list(res2))

输出结果

[('A', 0), ('A', 1), ('A', 2), ('B', 0), ('B', 1), ('B', 2)]
[('A', 0), ('A', 1), ('A', 2), ('B', 0), ('B', 1), ('B', 2)]

注:product返回的是一个可迭代对象

实例2

def test(a,N):
    for i in product(a, repeat=N):
        print(i)

x = [0,1]
test(x,1)
test(x,2)
test(x,3)

输出结果

(0,)
(1,)
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值