是否有一种方法可以使用itertools访问每个单独的排列?不把所有东西都添加到列表中的排列?



我正在使用Python,我有一个字符串列表(大约30个)。我想找到它们的所有可能的排列,我正在使用itertools.permutations。基本上我想做的是,在我得到一个排列之后,我想用哈希库对它进行哈希,并根据一个特定的值进行检查,这个值是我从password。txt文件中得到的,然后再进行下一个排列。我不需要遍历另一个排列字符串列表并尝试访问所有的字符串。我不确定如何在不遍历另一个列表的情况下一次访问每个单独的排列,因为我无法将其存储在变量中,因为itertools。Permutations返回一个Permutations对象。我试图使用映射,但我不确定这是否有效,因为我的pyCharm没有任何结果。有办法做到这一点吗?我的代码如下:

temp = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1","2","3", "4","5"]
f = open("password.txt", "r") 
for i in range(10): 
t = f.readline() 
for i in range(1, len(temp) + 1): 
for x in map("".join, itertools.permutations(temp, i)):
encode = hashlib.md5(x.encode())
hex = encode.hexdigest() 
if fileLine.__contains__(hex): 
print "Found" 

itertools.permutations返回生成器。生成器通常打算在上迭代一次。如果需要多次迭代,可以将其存储在列表中,如下所示:

perm = list(itertools.permutations(temp, i))

你想要的整个代码看起来像这样:

temp = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1","2","3", "4","5"]
f = open("password.txt", "r") 
for file_line in f:
for i in range(1, len(temp) + 1):
perm = list(itertools.permutations(temp, i))

for p in perm:
word = ''.join(p)
encode = hashlib.md5(word.encode())
hex = encode.hexdigest()
if hex in file_line: 
print "Found"

还要注意,通常不应该直接调用命名为__contains__的方法——在这种情况下,您可能希望使用操作符in来代替。注意变量名—您已经在嵌套循环中两次使用i作为索引变量。

itertools。Permutations (temp, i)已经是一个生成器,您不需要列出它,只需定义一次并使用for循环迭代它:

temp = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", 
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1","2","3", "4","5"]
f = open("password.txt", "r") 
for _ in range(10): 
t = f.readline() 
for i in range(1, len(temp) + 1): 
iterator = itertools.permutations(temp, i)
for x in iterator:
encode = hashlib.md5(x.encode())
hex = encode.hexdigest() 
if fileLine.__contains__(hex): 
print("Found")

还有两件事,由于排列数快速爆炸,这仍然需要很长时间,第二:您是否使用python 2.7?在python 3.x中,print语句将失败。

最新更新