Python:当生成器表达式的值为itertools.产品物体

2024-04-19 12:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

为了更好地理解Python,我正在尝试深入研究我在网上找到的一些代码。你知道吗

这是我想要体验的代码片段:

from itertools import chain, product

def generate_groupings(word_length, glyph_sizes=(1,2)):
    cartesian_products = (
        product(glyph_sizes, repeat=r)
        for r in range(1, word_length + 1)
    )

这里,word_length是3。你知道吗

我试图评估cartesian_products生成器的内容。根据我在阅读this的答案后得到的信息,生成程序在作为集合的一部分调用之前不会迭代(因此不会产生值),因此我将生成程序放在了一个列表中:

list(cartesian_products)
Out[6]: 
[<itertools.product at 0x1025d1dc0>,
 <itertools.product at 0x1025d1e10>,
 <itertools.product at 0x1025d1f50>]

显然,我现在看到了生成器的内部,但是我希望得到比itertools.product对象的原始细节更具体的信息。有办法做到这一点吗?你知道吗


Tags: 代码from程序信息productlengthatword
1条回答
网友
1楼 · 发布于 2024-04-19 12:40:24

如果您不想耗尽发电机,可以使用:

list(map(list,cartesian_products))

您将获得word_length = 3的以下内容

Out[1]:
[[(1,), (2,)],
 [(1, 1), (1, 2), (2, 1), (2, 2)],
 [(1, 1, 1),
  (1, 1, 2),
  (1, 2, 1),
  (1, 2, 2),
  (2, 1, 1),
  (2, 1, 2),
  (2, 2, 1),
  (2, 2, 2)]]

相关问题 更多 >