Python 3.x 如何在product for循环中调用元素

Python 3.x 如何在product for循环中调用元素,python-3.x,product,itertools,Python 3.x,Product,Itertools,我想将此嵌套循环替换为itertools.product: seasons = ['long', 'short'] weathers = ['dry', 'wet', 'sunny'] for season in seasons: for weather in weathers: output = "S= " + season + "&" + "W= " + weather print(

我想将此嵌套循环替换为
itertools.product

seasons = ['long', 'short']
weathers = ['dry', 'wet', 'sunny']

for season in seasons:
    for weather in weathers:
        output = "S= " + season + "&" + "W= " + weather
        print(output)
from itertools import product

seasons = ['long', 'short']
weathers = ['dry', 'wet', 'sunny']

for season, weather in product(seasons, weathers):
    output = "S= " + season + "&" + "W= " + weather
    print(output)
输出

S= long&W= dry
S= long&W= wet
S= long&W= sunny
S= short&W= dry
S= short&W= wet
S= short&W= sunny
我知道我可以使用以下方法打印所有元素:

mylist = list([seasons, weathers])
for element in itertools.product(*mylist):
    print(element)

但是如何调用
itertools.product
中的单个元素?

您可以在for循环中使用两个变量(来解压
product
返回的元组):

输出:

S= long&W= dry
S= long&W= wet
S= long&W= sunny
S= short&W= dry
S= short&W= wet
S= short&W= sunny

我不明白你在问什么。在上一个示例中,您不是在打印单个元素吗?也许你应该给出一个小例子,说明你到底想实现什么。我想实现相同的输出,但是使用
itertools.product
而不是嵌套的for循环。是的,它实现了。谢谢。注意:这是您在此场景中应该使用的
产品
,以及预期的使用方式。像许多生成
元组的
itertools
模块一样(像
zip
),当请求输出时返回的
元组未使用时,它有一个优化的快速路径;通过解包,您可以立即释放
元组
,这样就可以使用快速路径。这应该是:“当请求下一个输出时”,当然,我只是在编辑宽限期到期后才注意到这一点。