【发布时间】:2018-09-30 08:32:46
【问题描述】:
我需要获取单词列表并返回原始列表中找到的回文列表。我有可以做到这一点的代码,但如果列表不需要包含任何回文,它需要打印一个声明,说没有找到。
我在这里查看了有关如何检查列表是否为空的其他问题/答案,但我找不到任何与我的函数相关的内容,我在 for 循环中创建列表,并且需要检查我正在创建的列表是否包含任何内容。我发现的例子只是检查预制列表。
这是用于创建所需格式的回文列表的代码:
def is_palindrome(words):
"""Returns the palindromes from a list of words."""
print("\nThe following palindromes were found: ")
for word in words:
if word == word[::-1] and len(word) >= 3:
print(' -', word)
这是我的尝试:
def is_palindrome(words):
"""Returns the palindromes from a list of words."""
print("\nThe following palindromes were found: ")
palindromes = []
for word in words:
if word == word[::-1] and len(word) >= 3:
palindromes.append(word)
if palindromes != []:
print(' -', word)
else:
print('None found...')
但从未打印过“未找到”。
非常感谢您提供有关我哪里出错的建议,谢谢。
【问题讨论】:
-
一个空列表等于 False,所以你只需要
if palindromes: -
解决方法有问题吗?
-
这个函数打印回文,但它返回
None。它不应该返回回文列表吗?
标签: python list printing palindrome