返回朋友名字的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]