Filter A List According To Condition In Python
i need to calculate how much numbers form string got value higher or equal to 25 and lower or equal to 50 numbers = [25, 24, 26, 45, 25, 23, 50, 51] # 'count' should be 5 count
Solution 1:
numbers = [25, 24, 26, 45, 25, 23, 50, 51]
count = len(numbers)
filtered = [num for num in numbers if 25 < num <= 50]
count -= len(filtered)
Solution 2:
I need to filter all numbers and only numbers what are higher than 25 can stay
you can use the built-in function filter
:
numbers = [25, 24, 26, 45, 25, 23, 50, 51]
filtred = list(filter(lambda x : x > 25, numbers))
# [26, 45, 50, 51]
how much numbers form string got value higher or equal to 25 and lower or equal to 50
you can use the built-in function sum
:
count = sum(1 for e in numbers if e >= 25 and e<= 50)
# 5
Solution 3:
This should help
numbers = [25, 24, 26, 45, 25, 23, 50, 51]
count=0
f=[]
for i in numbers:
if i>=25 and i<=50:
f.append(i)
count+=1
print(f)
Solution 4:
A simple way to do it would be to create an empty list, iterate through the current list and append all relevant items to the new list, like so:
numbers = [25, 24, 26, 45, 25, 23, 50, 51]
new_list =[]
for i in numbers:
if i>=25 and i<=50:
new_list.append(i)
print(new_list)
Post a Comment for "Filter A List According To Condition In Python"