Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 难以检测空列表_Python_List_Printing_Palindrome - Fatal编程技术网

Python 难以检测空列表

Python 难以检测空列表,python,list,printing,palindrome,Python,List,Printing,Palindrome,我需要获取一个单词列表,并返回在原始列表中找到的回文列表。我已经得到了可以实现这一点的代码,但是如果列表不需要包含任何回文,它需要打印一条语句,说明找不到任何回文 我在这里查看了关于如何检查列表是否为空的其他问题/答案,但是我找不到任何与我的函数相关的问题/答案,我正在for循环中创建列表,并且需要检查我正在创建的列表是否包含任何内容。我发现的例子只是检查预先制作的列表 这是以所需格式创建回文列表的代码: def is_palindrome(words): """Returns the

我需要获取一个单词列表,并返回在原始列表中找到的回文列表。我已经得到了可以实现这一点的代码,但是如果列表不需要包含任何回文,它需要打印一条语句,说明找不到任何回文

我在这里查看了关于如何检查列表是否为空的其他问题/答案,但是我找不到任何与我的函数相关的问题/答案,我正在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...')
但“未找到”从未打印过

如果您能告诉我哪里出了问题,我们将不胜感激。请尝试以下方法:

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...')
或:


只要做
而不是

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

空列表等于False,因此如果回文:
解决方案有问题吗?此函数打印回文,但返回
None
。它不应该返回回文列表吗?根据PEP8,第一种方法通常不建议使用,尽管它工作得很好。@NChauhan是的,同意你的观点,第一个例子不应该使用。@U9 Forward这两种方法都是可以接受的,仅供参考检查文档
palindromes = []
for word in words:
    if word == word[::-1] and len(word) >= 3:
        palindromes.append(word)
if not palindromes:
    print('None found...')