从 aaaa 到 zzzz python
Go from aaaa to zzzz python
我需要找到一种使用 python(aaaa、aaab、aaac...zzzz)从 aaaa 暴力破解到 zzzz 的方法。
类似于 0000 到 9999。
有使用循环和列表的“神奇”方法吗?
这是一个非常“基本”的例子:
chars = 'abcdefghijklmnopqrstuvwxyz'
my_list = []
for c1 in chars:
for c2 in chars:
for c3 in chars:
for c4 in chars:
my_list.append(c1+c2+c3+c4)
print(my_list)
您可以使用 itertools.product
:
简洁地完成此操作
import itertools
import string
for elem in itertools.product(string.ascii_lowercase, repeat=5):
...
这是通过这种方法产生的前 30 个值的示例:
>>> values = itertools.product(string.ascii_lowercase, repeat=5)
>>> print(list(itertools.islice(values, 30)))
[
('a', 'a', 'a', 'a', 'a'),
('a', 'a', 'a', 'a', 'b'),
('a', 'a', 'a', 'a', 'c'),
# --Snip --
('a', 'a', 'a', 'a', 'x'),
('a', 'a', 'a', 'a', 'y'),
('a', 'a', 'a', 'a', 'z'),
('a', 'a', 'a', 'b', 'a'),
('a', 'a', 'a', 'b', 'b'),
('a', 'a', 'a', 'b', 'c'),
('a', 'a', 'a', 'b', 'd')
]
请注意,此序列中有 26**5 == 11881376
个值,因此您可能不想将它们全部存储在一个列表中。在我的系统上,这样一个列表大约占100 MiB。
很难知道你认为什么是“神奇的”,但我没有看到循环中的魔法。
这是一种变体:
cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))
我需要找到一种使用 python(aaaa、aaab、aaac...zzzz)从 aaaa 暴力破解到 zzzz 的方法。 类似于 0000 到 9999。 有使用循环和列表的“神奇”方法吗?
这是一个非常“基本”的例子:
chars = 'abcdefghijklmnopqrstuvwxyz'
my_list = []
for c1 in chars:
for c2 in chars:
for c3 in chars:
for c4 in chars:
my_list.append(c1+c2+c3+c4)
print(my_list)
您可以使用 itertools.product
:
import itertools
import string
for elem in itertools.product(string.ascii_lowercase, repeat=5):
...
这是通过这种方法产生的前 30 个值的示例:
>>> values = itertools.product(string.ascii_lowercase, repeat=5)
>>> print(list(itertools.islice(values, 30)))
[
('a', 'a', 'a', 'a', 'a'),
('a', 'a', 'a', 'a', 'b'),
('a', 'a', 'a', 'a', 'c'),
# --Snip --
('a', 'a', 'a', 'a', 'x'),
('a', 'a', 'a', 'a', 'y'),
('a', 'a', 'a', 'a', 'z'),
('a', 'a', 'a', 'b', 'a'),
('a', 'a', 'a', 'b', 'b'),
('a', 'a', 'a', 'b', 'c'),
('a', 'a', 'a', 'b', 'd')
]
请注意,此序列中有 26**5 == 11881376
个值,因此您可能不想将它们全部存储在一个列表中。在我的系统上,这样一个列表大约占100 MiB。
很难知道你认为什么是“神奇的”,但我没有看到循环中的魔法。
这是一种变体:
cs = 'abcdefghijklmnopqrstuvwxyz'
list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs]))