You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错‘list’ object has no attribute ‘replace’,实现Polybius方阵加密指定输出

Polybius方阵加密:将字符转为连续数字的问题

我正在编写将单词通过Polybius方阵加密为数字的代码,期望输出为连续数字(如41)而非坐标格式(4, 1)。但使用item.replace去除多余字符时,出现'list' object has no attribute 'replace'报错,尝试多种方法仍无法处理列表元素中的多余字符,该如何实现预期输出?

我的代码如下:

import numpy as np
polybius_square = np.array([["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"]])
word = str(input("Enter a word"))
wordletters = list(word)
numbers = []
print(wordletters)
print(len(wordletters))
for count in range(0,len(wordletters)):
  solutions = np.argwhere(polybius_square == wordletters[count])
  solutions = solutions.tolist()
  solutions = [item.replace(3, 10) for item in solutions]
  print(solutions)
  numbers.append(solutions)
  print(numbers)
print(*numbers, sep=" ")

我尝试了几种方法,但都无法去除列表中元素的多余字符。


解决方案

你报错的核心原因是:solutions.tolist()返回的是嵌套列表(比如匹配字符'p'会得到[[3, 0]]),每个item是子列表,而列表没有replace方法。另外,Polybius方阵的坐标是1-based(行、列从1开始计数),但numpy的索引是0-based,需要先做转换,再拼接成连续数字。

修改后的完整代码

import numpy as np

polybius_square = np.array([
    ["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"]
])

word = input("Enter a word: ").lower()  # 转小写确保和方阵字符匹配
encrypted = []

for letter in word:
    # 取出字符在方阵中的0-based坐标
    pos = np.argwhere(polybius_square == letter)[0]
    # 转换为1-based坐标,拼接成连续数字字符串
    code = f"{pos[0]+1}{pos[1]+1}"
    encrypted.append(code)

# 输出连续的加密数字
print("".join(encrypted))

关键说明

  1. 简化循环逻辑:用for letter in word替代索引循环,更直观简洁。
  2. 坐标转换:将numpy返回的0-based索引加1,得到Polybius标准的1-based坐标。
  3. 拼接数字:用f-string直接把行号和列号拼接成连续字符串,避免处理列表格式问题。
  4. 输出结果:用"".join(encrypted)直接输出连续数字串,比如输入"hello"会输出"2315333415"。

特殊字符处理(如'z')

如果需要支持'z',通常将其映射到(5,5),可以在循环中添加判断:

for letter in word:
    if letter == 'z':
        code = "55"
    else:
        pos = np.argwhere(polybius_square == letter)[0]
        code = f"{pos[0]+1}{pos[1]+1}"
    encrypted.append(code)

内容的提问来源于stack exchange,提问作者Hades BrawlStars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 04:47:16