data = [1, 5, -3, -2, 6, 0, 9]
res = []
for x in data:
if x >= 0:
res.append(x)
print(res)
列表:過濾掉列表中的負(fù)數(shù)
from random import randint
data = [randint(-10, 10) for _ in range(10)]
# 方式一 filter + lambda
res = filter(lambda x: x >= 0, data) # python3 中為迭代器慧妄,需要for循環(huán)進(jìn)行遍歷
for item in res:
print(item)
# 方式二 列表生成式(推薦)
res = [x for x in data if x >= 0]
print(res)
字典:過濾字典中值大于90的值
from random import randint
data = {x: randint(0, 100) for x in range(1, 21)}
res = {k: v for k, v in data.items() if v > 90}
集合:過濾集合中能被3整除的元素
from random import randint
data = [randint(-10, 10) for _ in range(10)]
s = set(data)
res = {x for x in s if x % 3 == 0}
print(res)