迭代方式(Low)
data = [1, 5, -3, -2, 6, 0, 9]
res = []
for x in data:
if x >= 0:
res.append(x)
print(res)
列表:过滤掉列表中的负数
from random import randint
data = [randint(-10, 10) for _ in range(10)]
# 方式一 filter + lambda
res = filter(lambda x: x >= 0, data) # python3 中为迭代器,需要for循环进行遍历
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)
网友评论