python 如何在列表list,字典dict,集合set 中根据条件筛选数据

from random import randint
"""
list 过滤掉负数
"""
data = [randint(-10, 10) for _ in xrange(10)]
print data
#  [7, 2, -5, -5, 2, -4, -7, 6, -9, 9]
d1 = filter(lambda x: x >= 0, data)
print d1
# [7, 2, 2, 6, 9]
# -------   这个快
d2 = [x for x in data if x >= 0]
print d2
# [7, 2, 2, 6, 9]

 

 

from random import randint
"""
dict  过滤 分数 高于 90的
"""
d = {x: randint(60, 100) for x in xrange(1, 21)}
print d
#{1: 65, 2: 92, 3: 78, 4: 66, 5: 88, 6: 93, 7: 69, 8: 82, 9: 80, 10: 76, 11: 85, 12: 90, 13: 66, 14: 90, 15: 60, 16: 99, 17: 65, 18: 74, 19: 86, 20: 95}
f_d = {k: v for k, v in d.iteritems() if v > 90}
print f_d
# {16: 99, 2: 92, 20: 95, 6: 93}

 

from random import randint
"""
set 找出被3整除的数
"""
data = [randint(-10, 10) for _ in xrange(10)]
s = set(data)
print s
# set([1, 4, 6, -1, -9, -7, -3, -2])
print {x for x in s if x % 3 == 0}
# set([-3, 6, -9])

 

posted @ 2019-04-07 21:35  AngDH  阅读(3505)  评论(0编辑  收藏  举报