使用函数定义的回文列表

2024-10-01 09:38:10 发布

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

input_list = ['tacocat', 'bob', 'davey']

def palindromes(input_list):
    for word in input_list:
        if input_list[word]==reversed(input_list[word]):
            print("True")
        else:
            print("False")

output=palindromes(input_list)
print(output)

输出应该是[True, True, False] 但这给了我错误


Tags: infalsetrueforinputoutputifdef
3条回答

这是您的代码修复程序,存在许多问题:

  1. 您正在打印,而不是实际输出任何内容(我添加了一个输出列表和一个return语句)
  2. 您试图错误地分割input_list(只需使用word
  3. reversed确实返回迭代器,因此匹配项始终为False(改用[::-1]
def palindromes(input_list):
    out = []
    for word in input_list:
        if word==word[::-1]:
            out.append("True")  # used strings here, maybe you wanted booleans?
        else:
            out.append("False")
    return out

output=palindromes(input_list)

也就是说,这里有一个简短的版本:

[w==w[::-1] for w in input_list]

输出:

[True, True, False]

如果您编写返回语句而不是打印,那么它就可以工作了。还可以尝试只调用函数而不指定任何变量

反转字符串并检查

input_list = ['tacocat', 'bob', 'davey']
results = [x == x[::-1] for x in input_list]
print(results)

输出

[True, True, False]

相关问题 更多 >