无法将函数放入列表中

2024-05-19 21:10:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试创建一台enigma机器,它使用用户想要的尽可能多的转子。 所以,我创建了这个函数:def enigma(uncrypted_string,n_of_rotors):

为了实现这一点,我使用了一个定义lambda函数的循环,然后将它们放在一个列表中:

  rotors=[]
  crypted_string=[]
  for i in range(n_of_rotors):
    i= lambda character,current_number: chr((ord(character) + current_number - 97) % 26 + 97)
    rotors.append(i) 

然后我使用循环对每个字母加密多次

for char in uncrypted_string:
    current_letter = char
    position +=1
    for r in rotors:
      current_letter = rotors[r](current_letter,1)
    crypted_string.append(current_letter)

问题是我遇到了这个错误,我不知道如何重新编程我的机器来做同样的事情:

current_letter = rotors[r](current_letter,1)
TypeError: list indices must be integers or slices, not function

很明显,我在网上搜索了我得到的错误,但我没有找到任何与我的问题类似的东西。。。有人能帮我吗


Tags: oflambda函数in机器numberforstring
1条回答
网友
1楼 · 发布于 2024-05-19 21:10:26

出现此错误的原因是您试图使用函数访问列表转子的索引位置。正如错误所说,您只能使用整数或片访问索引

for r in rotors:循环中,r已经是一个函数,因为它正在遍历列表转子。因此,您不需要使用rotors[r]来使用函数r。 要修复代码,请替换

current_letter = rotors[r](current_letter,1)

current_letter = r(current_letter,1)

相关问题 更多 >