python - 过滤字符串列表并返回一个仅包含您朋友姓名的列表
问题描述
我正在学习 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
列表中。
解决方案
这是您的功能的固定版本,可以满足您的需求:
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']
推荐阅读
- drop-down-menu - 如何区分下拉菜单中选择的值
- python - 如何替换熊猫数据框中包含括号或数字的列中的那些条目?
- android - 在 RecycleView 中加载图像
- javascript - 观看在 Vue 中没有得到全部
- apache-nifi - 如何在 NIFI 中配置 listenerhttp 处理器
- javascript - Material Ui popover 不在正确的位置
- python - 要从一个类中调用一个函数,Python 是否会遍历该类的每个函数,直到找到要调用的函数?
- php - PHPMailer 标头 AddReplyTo
- mysql - MySQL Store Procedure - Setting AUTO_INCREMENT value
- azure-cosmosdb - Cosmos DB - ORDER BY clause only returns 1 document