返回朋友名字的list
题目描述
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he’s not…
Ex: Input = [“Ryan”, “Kieran”, “Jason”, “Yous”], Output = [“Ryan”, “Yous”]
Note: keep the original order of the names in the output.
我的实现
def friend(x):
return [e for e in x if len(e) == 4 ]
print(["Ryan", "Kieran", "Jason","Yours"])
最佳实践1
def friend(x):
return [f for f in x if len(f) == 4]
实现是一样的,使用列表解析实现的。
列表解析总结下
语法:
[expression for iter_val in iterable]
[expression for iter_val in iterable if cond_expr]
博客围绕返回朋友名字的列表展开,给出题目描述,即过滤字符串列表,仅保留长度为4的名字作为朋友名字。介绍了实现方法,采用列表解析实现,还总结了列表解析的语法,如 [expression for iter_val in iterable] 等。
638

被折叠的 条评论
为什么被折叠?



