如何在 Python 中重复获得每个 6 元素排列?

How do I get every 6-element permutation with repetition in Python?

我想从 "abcdefghijklmnopqrstuvwxyz0123456789" 创建一个包含所有可能的 6 元素排列的列表,因此例如它应该输出:

['aaaaaa','aaaaab','aaaaac'...,'aaaaa0','aaaaa1'...,'aaaaba','aaaabb'...]等等。

这是我试过的:

import itertools

dictionary = 'abcdefghijklmnopqrstuvwxyz0123456789'
print(list(itertools.product(dictionary, repeat=6)))

但是我 运行 变成了 MemoryError 然后我的电脑完全死机了,那么有没有更有效的方法来计算这个列表?

(我使用的是 Python 3.8 64 位)

你知道你的清单有多长吗?是 36**6 = 2176782336 项。有点太多了,无法保留在内存中。你应该使用发电机:

dictionary = 'abcdefghijklmnopqrstuvwxyz0123456789'
for x in itertools.product(dictionary, repeat=6):
    print(''.join(x))

排列的大小很大:36^6!那是 2176782336 个字符串。由于 python 存储单独对象的方式,python 中的 6 个字符的字符串已经相对较大。

from sys import getsizeof

getsizeof('aaaaaa') # 55

每个字符串 55 个字节,整个列表将近 120 GB。您的机器上可能没有太多内存。

如果您尝试将此迭代器转换为列表,它将立即生成所有排列。您可以做的是使用 itertools.product(dictionary, repeat=6) 返回的迭代器而不将其转换为列表。

for s in itertools.product(dictionary, repeat=6):
    # Do something with the string, such as writing it to a file.

在不知道你想用这个产品做什么的情况下,我不能具体告诉你如何优化它。但我仍然可以说,尝试将此迭代器转换为 list 是个坏主意。