[英]Create a filtered list from a list with a for loop
I want to create a function which creates a new List from a List with a for loop.我想创建一个函数,该函数从带有 for 循环的列表中创建一个新列表。 In the new List should just be int and float in a range from 1 to 49.在新的 List 中应该只是 int 并且在 1 到 49 的范围内浮动。
Like:喜欢:
filter_list[2,3,55,"test",10]=[2,3,10]
how can i create such a list with a for loop?如何使用 for 循环创建这样的列表?
Edit: My code so far:编辑:到目前为止我的代码:
def filter_list(elements):
list = []
for i in elements:
if i in range(1,50):
list.append(i)
return list
but when i want to proof if its int or float with但是当我想证明它是 int 还是 float 时
isinstance(i,str)
it does not work probably它可能不起作用
You could use filter
:您可以使用filter
:
def filter_list(l):
return list(filter(lambda x: (isinstance(x, int) or isinstance(x, float)) and 1 <= x <= 49, l))
For python2, you won't need to convert the result of filter
to a list.对于python2,您不需要将filter
的结果转换为列表。 But for python3, you'll need the conversion.但是对于python3,您需要进行转换。
And you'll call it this way:你会这样称呼它:
>>> filter_list([2,3,55,"test",10])
[2, 3, 10]
Or simply use a list comprehension:或者简单地使用列表理解:
def filter_list(l):
return [x for x in l if (isinstance(x, int) or isinstance(x, float)) and 1 <= x <= 49]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.