Python - 回文函数 : Receiving error "list indices must be integers or slices, not str"

标签 python function ipython palindrome words

<分区>

我一直在尝试使用以下代码来创建回文。我有一个名为“lowercasewords”的 txt 文件,它本质上是一个充满小写单词的列表,我从中查询,我想将拼写相同的单词附加到名为“lines2”的列表中。

代码如下:

def palindrome():
    lines = open('lowercasewords.txt','r').read().splitlines()
    lines2 = []
    for x in lines:
        if (lines[x]) == (lines[x][::-1]) is True:
            lines2.append(str(x))
        else:
            pass
    print(lines2)

但是,我收到错误:

TypeError: list indices must be integers or slices, not str

谁能帮忙???我可以证明“级别”这个词是相同的颠倒:

str(lines[106102]) == str(lines[106102][::-1])
True

最佳答案

当您运行 for x in lines: 时,x 将设置为列表中的当前单词。然后,您的代码会尝试在 lines 中获取该词的索引。这相当于说 lines["hello"],没有任何意义。循环已经将 x 设置为您想要的值,因此您无需再引用 lines

您也不需要检查某事是否为 True,if 语句已经在测试语句是否为 Truefalse

你可以通过简单地替换来修复它

if (lines[x]) == (lines[x][::-1]) is True:

if x == x[::-1]:

关于Python - 回文函数 : Receiving error "list indices must be integers or slices, not str",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47267873/

相关文章:

Python:检查用户对 raw_input() 的响应

ipython - 如何在 ipython 中重新加载类定义

python - 如何在下一个 jupyter 单元格中重复使用 plot

matlab - 等效于 Lua 解释器的 Matlab "whos"命令?

python - 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素?

Python + 开罗 : How Do I Save a Drawing?

java - Appengine 上 google Go 与 Python 和 Java 的资源使用情况

python - unittest 将变量作为参数传递

python - Python 3.x 中新的 print 函数相对于 Python 2 的 print 语句有什么优势?

Swift - 在扩展函数中呈现 UIAlertController