简体   繁体   English

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

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

I want to create a list of all possible 6-element permutations from "abcdefghijklmnopqrstuvwxyz0123456789" so for example it should output:我想从“abcdefghijklmnopqrstuvwxyz0123456789”创建一个所有可能的 6 元素排列的列表,例如它应该是 output:

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

This is what I tried:这是我尝试过的:

import itertools

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

but I ran into a MemoryError and then my computer froze up completely, so is there a more efficient way to compute this list?但是我遇到了MemoryError ,然后我的计算机完全死机了,那么有没有更有效的方法来计算这个列表?

(I'm using Python 3.8 64-bit) (我正在使用 Python 3.8 64 位)

Do you know how long your list would be?你知道你的名单会有多长吗? It is 36**6 = 2176782336 items.它是 36**6 = 2176782336 项。 A bit too much to hold in memory. memory 有点太多了。 You should have used a generator:您应该使用生成器:

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

The size of the permutation is huge: 36^6.排列的大小很大:36^6。 That's 2176782336 strings.那是 2176782336 个字符串。 A 6-char string in python is already relatively large due to how python stores separate objects.由于 python 存储单独对象的方式,python 中的 6 字符字符串已经相对较大。

from sys import getsizeof

getsizeof('aaaaaa') # 55

At 55 bytes per string, the whole list is almost 120 Gigabytes.每个字符串 55 个字节,整个列表几乎是 120 GB。 You probably don't much have memory on your machine.您的机器上可能没有多少 memory。

If you try to convert this iterator to a list, it will generate all permutations at once.如果您尝试将此迭代器转换为列表,它将立即生成所有排列。 What you can do instead is to use the iterator returned by itertools.product(dictionary, repeat=6) without converting it to a list.您可以做的是使用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.

Without knowing what you are trying to do with the product, I can't specifically tell you how to optimize this.在不知道您要对产品做什么的情况下,我无法具体告诉您如何优化它。 But I can still say that trying to convert this iterator to a list is a bad idea.但我仍然可以说尝试将此迭代器转换为list是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM