为什么这个程序没有返回?

2024-06-16 12:56:21 发布

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

当我们传递numbern和字符串列表时,如何创建Python自定义函数来获取长度超过一个数n的字符串列表

我尝试使用此函数,但它返回None

lst=['shiva', 'patel', 'ram','krishna', 'bran']
filtered_list=[]
def word_remove(n, lst):
    for i in lst:
        if len(i)>n:
            return filtered_list.append(i)
print(word_remove(4,lst))

输出为:

None

Tags: 函数字符串none列表removefilteredlistword
3条回答

列表上的append方法不返回任何值。因此None类型

lst = ['shiva', 'patel', 'ram','krishna', 'bran']

filtered_list=[]

def word_remove(n, lst):
    for i in lst:
        if len(i)>n:
            filtered_list.append(i)
    return filtered_list

print (word_remove(4,lst))

输出:

['shiva', 'patel', 'krishna']

append方法不返回任何内容。因此,您需要返回整个过滤的列表

Append函数没有返回类型。试试这个

def word_remove(n, lst):
    for i in lst:
        if len(i) > n:
            filtered_list.append(i)
    return filtered_list

相关问题 更多 >