为唯一列表创建正确的 for-loop/iteration

Creating correct for-loop/iteration for a unique list

我有一个数字 1、2、3 和 4 的列表。

我希望通过以下方式打印出来:

1
2
3
4
11
12
13
14
21
22
23
24
31

..等等。

这怎么可能? 谢谢

from itertools import product

maximumDigits = 2
digits = '1234'
for l in range(1, maximumDigits + 1):
    for n in product(digits, repeat=l):
        print(''.join(n))

给你:

1
2
3
4
11
12
13
14
21
22
23
24
31
32
33
34
41
42
43
44

非itertools解决方案:

>>> digits = (1, 2, 3, 4)
>>> nums = newNums = list(digits)

# calculate 2-digit numbers
>>> newNums = [n * 10 + m for n in newNums for m in digits]
>>> nums.extend(newNums)
>>> nums
[1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44]

# calculate 3-digit numbers
>>> newNums = [n * 10 + m for n in newNums for m in digits]
>>> nums.extend(newNums)
>>> nums
[1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 111, 112, 113, 114, 121, 122, 123, 124, 131, 132, 133, 134, 141, 142, 143, 144, 211, 212, 213, 214, 221, 222, 223, 224, 231, 232, 233, 234, 241, 242, 243, 244, 311, 312, 313, 314, 321, 322, 323, 324, 331, 332, 333, 334, 341, 342, 343, 344, 411, 412, 413, 414, 421, 422, 423, 424, 431, 432, 433, 434, 441, 442, 443, 444]

# this repeats for each new digit you want