【集合】列表生成式以及过滤器的使用

from random import randint

'''
    列表生成式、过滤器的使用
'''

# 1.过滤列表中的负数
# 法1
data = [randint(-10, 10) for i in range(10)]
print(data)
f_list = filter(lambda x: x >= 0, data)
print(list(f_list))

# 法2
print([i for i in data if i >= 0])

print('-' * 50)
# 2.筛选成绩大于80分的
d = {str(i): randint(1, 100) for i in range(0, 50)}
print(d)
# 法1
f_dict = filter(lambda x: x > 80, d.values())
print(list(f_dict))

# 法2
print([v for v in d.values() if v > 80])

print('-' * 50)
# 3.筛选出集合中能被3整除的数
l_set = set([randint(1, 100) for x in range(100)])
# 法1
print(list(filter(lambda i: i % 3 == 0, l_set)))

# 法2
print([i for i in l_set if i % 3 == 0])

运行结果

[2, 0, -9, 9, -1, -5, 7, -3, -6, 8]
[2, 0, 9, 7, 8]
[2, 0, 9, 7, 8]
--------------------------------------------------
{'0': 56, '1': 25, '2': 71, '3': 56, '4': 44, '5': 13, '6': 90, '7': 2, '8': 33, '9': 16, '10': 47, '11': 12, '12': 66, '13': 48, '14': 32, '15': 41, '16': 48, '17': 62, '18': 16, '19': 100, '20': 22, '21': 57, '22': 21, '23': 92, '24': 56, '25': 7, '26': 11, '27': 33, '28': 79, '29': 31, '30': 14, '31': 85, '32': 96, '33': 28, '34': 100, '35': 44, '36': 51, '37': 84, '38': 99, '39': 19, '40': 38, '41': 41, '42': 6, '43': 8, '44': 62, '45': 78, '46': 86, '47': 4, '48': 26, '49': 63}
[90, 100, 92, 85, 96, 100, 84, 99, 86]
[90, 100, 92, 85, 96, 100, 84, 99, 86]
--------------------------------------------------
[3, 6, 15, 18, 30, 33, 36, 39, 42, 45, 54, 57, 60, 63, 72, 75, 78, 81, 84, 90, 93, 96, 99]
[3, 6, 15, 18, 30, 33, 36, 39, 42, 45, 54, 57, 60, 63, 72, 75, 78, 81, 84, 90, 93, 96, 99]

posted @ 2019-10-10 22:49  孙^_^川先生  阅读(163)  评论(0编辑  收藏  举报