Message='itertools.permutations' object is not subscriptable Source=E:\1daer\mmxdzy\1\dzy1\dzy1.py StackTrace: File "E:\1daer\mmxdzy\1\dzy1\dzy1.py", line 55, in guess_key1 print(next(mp[i][j]), end=" ") ~~~~~^^^ File "E:\1daer\mmxdzy\1\dzy1\dzy1.py", line 79, in <module> (Current frame) print(guess_key1(cipher_text, words)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'itertools.permutations' object is not subscriptable
时间: 2023-07-31 22:13:38 浏览: 182
Python标准库itertools的使用方法
这个错误是因为您在使用 `next(mp[i][j])` 时,将 `mp[i][j]` 当做了一个可索引的对象,但实际上 `mp[i][j]` 是一个 `itertools.permutations` 对象,不支持索引操作。
如果您想获取 `itertools.permutations` 中的某个元素,可以将其转换为列表或元组,然后再进行索引操作。例如,您可以将 `next(mp[i][j])` 改为 `list(mp[i][j])[0]`,这样就可以获取排列中的第一个元素。
以下是修正后的示例代码:
``` python
import itertools
def guess_key1(cipher_text, words):
# 生成字符组合的排列
perms = itertools.permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 5)
for perm in perms:
# 将排列转换为字典
key = {chr(i+65): perm[i] for i in range(26)}
# 解密密文
plain_text = decrypt(cipher_text, key)
# 如果解密后的明文包含给定单词,则返回密钥
if contains_words(plain_text, words):
return key
def contains_words(text, words):
# 判断文本中是否包含给定单词
for word in words:
if word in text:
return True
return False
def decrypt(cipher_text, key):
# 解密密文
plain_text = ''
for ch in cipher_text:
if ch.isalpha():
plain_text += key[ch]
else:
plain_text += ch
return plain_text
cipher_text = 'LXYXKXOXRKXYXKXXKLYXKXXYXKXOXRKXYXKXXKLRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKXXYXKXXYXKXOXRKXYXKXXKLRKXXYXKXXYXKXOXRKXYXKXXKLOXKX'
words = ['CRYPTO', 'GOLD', 'SILVER']
# 获取排列器
perms = itertools.permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 5)
# 将排列器转换为二维列表
mp = [[0] * 5 for i in range(5)]
for i in range(5):
for j in range(5):
mp[i][j] = perms
# 遍历排列器中的每一个排列
for i in range(5):
for j in range(5):
# 获取排列器中的下一个排列
perm = next(mp[i][j])
# 输出排列中的第一个元素
print(list(perm)[0], end=" ")
print()
```
在上面的代码中,我们使用 `list(perm)[0]` 来获取排列中的第一个元素,然后输出到控制台上。
阅读全文