How to write code for filtering in Python?

The filtering function can be implemented using conditional statements and loops. Here is an example code:

# 假设有一个列表包含一些数字
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 筛选出偶数
even_numbers = []
for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)
        
print(even_numbers)  # 输出 [2, 4, 6, 8, 10]

# 筛选出大于5的数字
greater_than_5 = []
for number in numbers:
    if number > 5:
        greater_than_5.append(number)
        
print(greater_than_5)  # 输出 [6, 7, 8, 9, 10]

# 使用列表推导式简化筛选过程
even_numbers = [number for number in numbers if number % 2 == 0]
greater_than_5 = [number for number in numbers if number > 5]

print(even_numbers)  # 输出 [2, 4, 6, 8, 10]
print(greater_than_5)  # 输出 [6, 7, 8, 9, 10]

The code above first filters the elements in the list using loops and conditional statements, adding the elements that meet the conditions to the corresponding new list. Then, it simplifies the filtering process using list comprehension, adding each element that meets the conditions to the new list. Finally, it outputs the results of the two new lists separately.

bannerAds