首页 > 解决方案 > 过滤字符串列表并返回一个仅包含您朋友姓名的列表

问题描述

我正在学习 Python 并试图解决同样的问题(“朋友还是敌人?”)。我编写了下面的代码,并想了解如何按照“我的逻辑”方式继续前进。

它似乎只将第一项添加到new_friends列表中,但没有遍历x列表的所有元素。

除了上面,返回值是None......我在这里没有注意到什么?

def friend(x):
    x = ["Ryan", "Kieran", "Jason", "Yous"]
    new_friends = []
    for str in x:
        if len(str) == 4:
            return new_friends.append(str)
    return new_friends[0:]

而不是if声明,我还尝试了一个嵌套while循环..但没有成功将其他项目添加到new_friends列表中。

标签: pythonlist

解决方案


这是您的功能的固定版本,可以满足您的需求:

def friend(x):
    new_friends = []
    for str in x:
        if len(str) == 4:
            new_friends.append(str) # no 'return' here
    return new_friends # return resulting list.  no need to return a slice of it

这是一个使用列表推导的更简洁的版本:

def friend(candidates):
    return [candidate for candidate in candidates if len(candidate) == 4]

对于任一版本的函数,这:

print(friend(["Ryan", "Kieran", "Jason", "Yous"]))

结果是:

['Ryan', 'Yous']

推荐阅读