传统迭代法
data = [1,5,-3,-2,8,0,9]
res = []
for x in data:
if x >=0:
res.append(x)
print(res)
python中更好的解决方案
- 列表
- filter函数
filter(lambda x:x>=0,data)
from random import randint
data = [randint(-10,10) for x in range(10)]
a = filter(lambda x:x>=0,data)
print(data)
#在python3中需要list(a)这一步,python2不需要这步
# 原因是在python3中,map函数仅仅是创建一个待运行的命令容器
# 只有其他函数调用它的时候才返回结果
print(list(a))
- 列表解析
[x for x in data if x>=0]
,推荐使用列表解析
data = [1,5,-3,-2,8,0,9]
a = [x for x in data if x>=0]
print(list(a))
- 字典(字典解析)
{k:v for k,v in d.items() if v>90}
,python2用d.iteritems()
from random import randint
d = {x : randint(60,100) for x in range(1,21)}
print(d)
dict = {k:v for k,v in d.items() if v>90}
print(dict)
- 集合(集合解析)
{x for x in s if x%3==0}
from random import randint
data = [randint(-10,10) for x in range(10)]
print(data)
s = {x for x in data if x % 3 ==0}
print(s)