How can Python filter according to specified conditions?
In Python, you can use conditional statements to filter data based on specified conditions. Here is an example code snippet:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 筛选出偶数
even_numbers = [num for num in data if num % 2 == 0]
print(even_numbers) # 输出: [2, 4, 6, 8, 10]
# 筛选出大于5的数
greater_than_5 = [num for num in data if num > 5]
print(greater_than_5) # 输出: [6, 7, 8, 9, 10]
# 筛选出能被3整除的数
divisible_by_3 = [num for num in data if num % 3 == 0]
print(divisible_by_3) # 输出: [3, 6, 9]
In this example, we use list comprehension to filter data. By adding a conditional statement at the end of the list comprehension, we can select elements to include in the new list based on a specified condition. Here, we use the % operator to check if a number can be divided by another number, and comparison operators to check if a number is greater than another number.