python - 如何在 Python 中制作包含多个变量的单行列表?

标签 python

我感兴趣的是我是否可以在一行中定义 ascii_combinations 列表而不使用我在以下示例中使用的循环...

ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = []

for x1 in ascii_printable:
    for x2 in ascii_printable:
        for x3 in ascii_printable:
            ascii_combinations.append(x1 + x2 + x3)

我想使用 95 个单字符 ASCII 字符创建一个包含所有可能的 3 个字符长组合的列表。我使用这段代码让它工作,但当我设法将 ascii_printable 缩短为 One-Liner 时,我很想知道我是否可以对另一个列表做同样的事情。

最佳答案

由于您想要创建笛卡尔积,标准方法是使用 itertools.product

import itertools

ascii_printable = [chr(count) for count in range(32, 127)]
ascii_combinations = [x1+x2+x3 for x1, x2, x3 in itertools.product(ascii_printable, repeat=3)]

关于python - 如何在 Python 中制作包含多个变量的单行列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39816176/

相关文章:

python - 输入在 python 3 中不起作用

python - coverage.py:排除文件

python - Opencv和python获取正确的文档构建并绘制图像

python - Django 值错误 : Missing staticfiles manifest entry for 'inline.bundle.js' runserver

python - django 生产服务器 - Django 未在 500 错误情况下向 ADMINS 发送邮件

python - 如何用 Python 拆分合并的 Excel 单元格?

python - 使用 OpenCV 进行网络摄像头颜色校准

python - 多项式长除法

python - 每个机器人的IP不同吗?

python循环遍历输入文件