如何在列表,字典,集合中根据条件筛选数据
1列表中筛选数据
1.1传统的筛选,比较麻烦且性能不好。
data=[1,7,8,5,7,3,6]
for x in data:
if x>5:
print(x)
1.2filter函数
from random import randint
data=[randint(-10, 10) for x in range(10)] # [-1, 6, -4, -5, 7, 3, -10, -8, 8, 0]
print(list(filter(lambda a:a>=1, data))) # [6, 7, 3, 8]
1.3列表解析
from random import randint
data=[randint(-10, 10) for x in range(10)] # [-8, -9, 8, 7, 2, 7, 0, -10, 10, 0]
print([x for x in data if x>=1]) # [8, 7, 2, 7, 10]
2字典中筛选数据
2.1 字典解析
from random import randint
d={x:randint(60,100) for x in range(1,21)} #随机生成21个同学的分数
# {1: 66, 2: 82, 3: 95, 4: 98, 5: 88, 6: 91, 7: 67, 8: 96, 9: 78, 10: 81, 11: 87, 12: 77, 13: 74, 14: 95, 15: 76, 16: 74, 17: 99, 18: 82, 19: 67, 20: 90}
print({k:v for k,v in d.items() if v>90}) # 选出分数大于90的同学
# {3: 95, 4: 98, 6: 91, 8: 96, 14: 95, 17: 99}
3集合中筛选数据
3.1 集合解析
from random import randint
data=[randint(-10, 10) for x in range(10)]
s = set(data) #列表变集合 {3, 5, 7, 8, 9, -6, -4, -1}
print({x for x in s if x%3==0}) # 集合中能除尽3的数据 {9, -6, 3}
附加
当大量索引访问降低程序可读性时,如何为元组中每个元素命名,提高程序可读性。
方法一:用变量代替索引值
name,age,sex,mail=range(4) #用变量代替索引值
Student= ('cocoa','20','male','485612@qq.com')
print(Student[name],Student[age],Student[sex],Student[mail]) # cocoa 20 male 485612@qq.com
print(Student[0],Student[1],Student[2],Student[3]) # cocoa 20 male 485612@qq.com
方法二:使用标准库中的collections.namedtuple代替tuple
from collections import namedtuple
Student = namedtuple('student', ['name','age','sex','mail'])
s= Student('cocoa','20','male','485612@qq.com')
print(s) # student(name='cocoa', age='20', sex='male', mail='485612@qq.com')
print(s.name,s.age,s.sex,s.mail) # cocoa 20 male 485612@qq.com
print(isinstance(s,tuple)) # 判断是nametuple类型的s是不是tuple的子类