[英]Create a function which takes a list as an argument and keeps only the numbers that are greater than 5
I am trying to create a function that takes a list as an argument and keeps only the numbers that are greater than 5 by creating a new empty list inside the function and only append it with numbers that are greater than five, looping over the given one.我正在尝试创建一个 function ,它以一个列表作为参数,并通过在 function 中创建一个新的空列表来仅保留大于 5 的数字,并且只有 append 它的数字大于五,循环遍历给定的一个. However, append does not return anything or it returns None.
但是,append 不返回任何内容或返回 None。
lst = [[0, 1, 5, 6, 9], [5, 5, 5, 5], [42, 1337], [-100, 100]]
def more_than_five(lst):
result = []
for i in range(len(lst)):
if i > 5:
result.append(i)
return result
Output should be (individually. not as one list):
[6,9]
[]
[42, 1337]
[100]
You can use a double comprehension to iterate over a list of lists:您可以使用双重理解来遍历列表列表:
def more_than_five(lst):
return [[i for i in l if i > 5] for l in lst]
print(more_than_five(lst))
# Output
[[6, 9], [], [42, 1337], [100]]
Without a comprehension:没有理解:
def more_than_five(lst):
result = []
for j, l in enumerate(lst):
result.append([])
for i in l:
if i > 5:
result[j].append(i)
return result
print(more_than_five(lst))
# Output
[[6, 9], [], [42, 1337], [100]]
Update : If your function only processes one list at a time:更新:如果您的 function 一次只处理一个列表:
def more_than_five(lst):
return [i for i in lst if i > 5]
print(more_than_five(lst[0]))
print(more_than_five(lst[1]))
# and so on
Or:或者:
def more_than_five(lst):
result = []
for i in lst:
if i > 5:
result.append(i)
return result
print(more_than_five(lst[0]))
print(more_than_five(lst[1]))
# and so on
Output: Output:
[6, 9]
[]
[42, 1337]
[100]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.