难以检测到空列表

时间:2018-09-30 08:32:47

标签: python list printing palindrome

我需要列出单词列表并返回原始列表中的回文列表。我已经找到了可以执行此操作的代码,但是如果列表不需要包含任何回文,则需要打印一条声明未找到回文的语句。

我在这里查看了其他有关如何检查列表是否为空的问题,但我找不到与我的函数相关的任何内容,我在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...')

但从未打印出“未找到”。

非常感谢关于我要去哪里的建议。

2 个答案:

答案 0 :(得分:1)

尝试一下:

for word in words:
    if word == word[::-1] and len(word) >= 3:
        palindromes.append(word)
        print('palindrome - ',word)
if len(palindromes)==0:
    print('None found...')

OR:

for word in words:
    if word == word[::-1] and len(word) >= 3:
        palindromes.append(word)
        print('palindrome - ',word)
if not palindromes:
    print('None found...')

答案 1 :(得分:1)

只需not

palindromes = []
for word in words:
    if word == word[::-1] and len(word) >= 3:
        palindromes.append(word)
if not palindromes:
    print('None found...')