I want to create a function which creates a new List from a List with a for loop. In the new List should just be int and float in a range from 1 to 49.
Like:
filter_list[2,3,55,"test",10]=[2,3,10]
how can i create such a list with a for loop?
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
isinstance(i,str)
it does not work probably
You could use 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. But for python3, you'll need the conversion.
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.