Python - 回文函数:接收错误"list indices must be integers or slices, not str"
Python - Palindrome function: Receiving error "list indices must be integers or slices, not str"
我一直在尝试使用以下代码来创建回文。我有一个名为 'lowercasewords' 的 txt 文件,它本质上是一个充满小写单词的列表,我从中查询,我想将拼写相同的单词附加到名为 'lines2'.[= 的列表中15=]
代码如下:
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
有人能帮忙吗???我可以证明单词 'level' 是相同的颠倒:
str(lines[106102]) == str(lines[106102][::-1])
True
当你 运行 for x in lines:
然后 x
被设置为列表中的当前单词。然后您的代码会尝试获取 lines
中该词的索引。这相当于说 lines["hello"]
,没有任何意义。循环已经将 x
设置为您想要的值,因此您不需要再参考 lines
。
您也不需要检查某些内容是否 is True
,if 语句已经在测试 True
或 false
.
的语句
您可以通过简单地替换
来修复它
if (lines[x]) == (lines[x][::-1]) is True:
和
if x == x[::-1]:
我一直在尝试使用以下代码来创建回文。我有一个名为 'lowercasewords' 的 txt 文件,它本质上是一个充满小写单词的列表,我从中查询,我想将拼写相同的单词附加到名为 'lines2'.[= 的列表中15=]
代码如下:
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
有人能帮忙吗???我可以证明单词 'level' 是相同的颠倒:
str(lines[106102]) == str(lines[106102][::-1])
True
当你 运行 for x in lines:
然后 x
被设置为列表中的当前单词。然后您的代码会尝试获取 lines
中该词的索引。这相当于说 lines["hello"]
,没有任何意义。循环已经将 x
设置为您想要的值,因此您不需要再参考 lines
。
您也不需要检查某些内容是否 is True
,if 语句已经在测试 True
或 false
.
您可以通过简单地替换
来修复它if (lines[x]) == (lines[x][::-1]) is True:
和
if x == x[::-1]: