在Python中筛选列表中大于0的数,你可以使用以下几种方法:
1. 使用`filter`函数和`lambda`匿名函数:
Ldata = [1, 2, 3, 4, 5, 6, -1, -2]
res1 = list(filter(lambda x: x > 0, Ldata))
print(res1) 输出:[1, 2, 3, 4, 5, 6]
2. 使用列表解析(List Comprehension):
Ldata = [1, 2, 3, 4, 5, 6, -1, -2]
res1 = [x for x in Ldata if x > 0]
print(res1) 输出:[1, 2, 3, 4, 5, 6]
3. 使用循环遍历列表:
def has_positive_numbers(lst):
for num in lst:
if num > 0:
return True
return False
lst1 = [-1, 0, -2, -3]
lst2 = [1, 0, -2, -3]
print(has_positive_numbers(lst1)) 输出:False
print(has_positive_numbers(lst2)) 输出:True
4. 使用`filter`函数和`list`函数转换结果:
from random import randint
data = [randint(-10, 10) for _ in range(10)]
res1 = list(filter(lambda x: x > 0, data))
print(res1) 输出:[5, 7, 9, 3, 3]
5. 使用列表解析:
data = [randint(-10, 10) for _ in range(10)]
res1 = [x for x in data if x > 0]
print(res1) 输出:[5, 7, 9, 3, 3]
以上方法都可以用来筛选列表中大于0的数。列表解析通常比`filter`函数更简洁且执行速度更快。