如何在Python中创建包含多个变量的One-Liner列表?

时间:2016-10-02 10:43:32

标签: 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时,我感兴趣的是我是否可以对其他列表做同样的事情。

3 个答案:

答案 0 :(得分:3)

由于您要创建笛卡尔积,因此标准方法是使用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)]

答案 1 :(得分:2)

您可以使用itertools.product作为

from itertools import product

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

同样chr(count) for count in range(32, 127)不如

明确
from itertools import product
from string import printable

ascii_combinations = [x1 + x2 + x3 for x1, x2, x3 in product(printable[:-5], repeat=3)]

最后,理解很好,但有时候根据迭代的地图来思考,imho更容易,因此

from itertools import product
from string import printable
list(map(''.join, product(printable[:-5], repeat=3)))

答案 2 :(得分:0)

结果为True:

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)

test = [x1+x2+x3 for x1 in ascii_printable for x2 in ascii_printable for x3 in ascii_printable]

print(test == ascii_combinations)