首页 > 解决方案 > 如何在 Python 中通过重复获得每个 6 元素排列?

问题描述

我想从“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 位)

标签: pythonpermutation

解决方案


你知道你的名单会有多长吗?它是 36**6 = 2176782336 项。有点太多记不住了。您应该使用生成器:

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

推荐阅读