Python列表、字典的筛选 Posted on 2017-05-25 Edited on 2024-02-03 In python , foundation 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env python#coding:utf-8from random import randint""" 列表筛选 生成一个有20个随机数的数组 data 从 data 列表中筛选出大于0的数字"""data = [randint(-100,100) for _ in xrange(10)]print data## 迭代def test1(d): s = [] for x in data: if x >=0: s.append(x) return s## 用filterdef test2(d): return filter(lambda x:x>=0,d)## 用列表解析def test3(d): return [x for x in data if x>=0]print test1(data)print test2(data)print test3(data)## 迭代最慢、列表解析最快""" 字典的筛选 生成键值在56-100之间的随机数10个 找出大于90的数"""data = {x:randint(56,100) for x in xrange(1,11)}print datadef test4(d): return {k:v for k,v in d.iteritems() if v>=90}print test4(data) 输出: 1234567[61, -31, 2, -45, -1, 19, -41, -8, -17, 48][61, 2, 19, 48][61, 2, 19, 48][61, 2, 19, 48]{1: 59, 2: 99, 3: 97, 4: 83, 5: 89, 6: 79, 7: 69, 8: 58, 9: 73, 10: 58}{2: 99, 3: 97}