L先生996 发表于 2025-10-22 14:42:12

请求帮助!

x = input("请输入明文:")
y = input("请输入的位数:")

a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
   "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
   "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--",
   "....-", ".....", "-....", "--...", "---..", "----.", "-----"]
x_code = list(x)
result = []
c = []
for e in x_code:
    if e in a:
      c_old = a.index(e)
      c_new = (c + int(y)) % len(a)
      new_result = a
      result.append(new_result)
    else:
      result.append(e)
print(''.join(result))

为什么?
错误:
请输入明文:LLL
请输入的位数:2
Traceback (most recent call last):
File "C:/Users/10690/Desktop/莫斯密码(进化).py", line 15, in <module>
    c_new = (c + int(y)) % len(a)
TypeError: can only concatenate list (not "int") to list

FishC 发表于 2025-10-22 14:43:54

您的代码出现了类型错误(TypeError),主要是因为变量 c 没有被正确初始化和使用。在循环中,您试图将列表类型的 c 与整数 int(y) 相加,但Python不允许这种操作。此外,代码中一些变量(如 result)没有初始化,会导致其他错误。

错误的具体原因:
- 在计算新索引时,使用了未定义的变量 c,而不是当前字符的索引 c_old。
- 变量 c 可能被错误地赋值为列表,但实际应该是一个整数。
- 变量 result 没有初始化为空列表,会导致 append 方法失败。

修正后的代码应该:
1. 初始化 result 为空列表。
2. 在循环中使用 c_old 而不是 c 来计算新索引。
3. 删除不必要的变量(如 b 和 c)。

以下是修正后的代码,它实现了凯撒密码加密功能(将明文根据指定位数移位):


x = input("请输入明文:")
y = input("请输入的位数:")
a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
x_code = list(x)
result = []# 初始化结果列表
for e in x_code:
    if e in a:
      c_old = a.index(e)# 获取当前字符在字母表中的索引
      c_new = (c_old + int(y)) % len(a)# 计算新索引
      new_result = a# 根据新索引获取字符
      result.append(new_result)
    else:
      result.append(e)# 非字母字符直接添加
print(''.join(result))


使用您的输入示例(明文"LLL",位数2),输出将是"NNN",因为L在字母表中索引为11,加2后取模得到13,对应字符N。

如果还有其他问题,请随时追问!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

不二如是 发表于 2025-10-22 17:44:46

原因非常明确:

TypeError: can only concatenate list (not "int") to list
意思是:鱼油试图把一个 list 和一个 int 相加。
问题出在这一行:

c_new = (c + int(y)) % len(a)
c 在程序中定义为:

c = []
也就是说它是一个 空列表。

但你在循环中其实是想对每个字母的索引(即整数 c_old)进行位移运算,而不是用列表 c。

正确写法:把 c 改成 c_old 就可以了:

x = input("请输入明文:")
y = input("请输入的位数:")

a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
   "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
   "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--",
   "....-", ".....", "-....", "--...", "---..", "----.", "-----"]

x_code = list(x)
result = []

for e in x_code:
    if e in a:
      c_old = a.index(e)
      c_new = (c_old + int(y)) % len(a)
      new_result = a
      result.append(new_result)
    else:
      result.append(e)

print(''.join(result))
页: [1]
查看完整版本: 请求帮助!