根据 Python 中的条件筛选列表

Filter a list according to condition in Python

我需要计算字符串中有多少数字的值高于或等于 25 且低于或等于 50

numbers = [25, 24, 26, 45, 25, 23, 50, 51]

#  'count' should be 5 
count = 0
# I need to filter all numbers and only numbers what are higher than 25 can stay 

numbers = [25, 24, 26, 45, 25, 23, 50, 51]

#  'filtered' should be equal to [26, 45, 50, 51]
filtered = []
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)

这应该有帮助

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)

I need to filter all numbers and only numbers what are higher than 25 can stay

你可以使用内置函数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

你可以使用内置函数sum:

count = sum(1 for e in numbers if e >= 25 and e<= 50)
# 5

一个简单的方法是创建一个空列表,遍历当前列表并将所有相关项目附加到新列表,如下所示:

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)