#!/usr/bin/env python # -*- coding:utf-8 -*- #2.1 如何在列表,字典,集合中根据天剑筛选数据 # 帅选列表中符合条件的项 data = [1,5,-3,-2,6,8,0,9] res = [] for x in data: if x >=0: res.append(x) # print(res) #2 from random import randint data = [randint(-10,10) for _ in xrange(10)] m = filter(lambda x:x>=0,data) # print(m) #3 这种方式更快 ,首选方式 m = [x for x in data if x>=0] # print(m) # 字典筛选 d = {x:randint(60,100) for x in xrange(1,21)} print(d) #1 m = {k:v for k,v in d.iteritems() if v >90} print(m) # 集合筛选 s = set(data) print(s) m = {x for x in s if x %3 ==0} print(m) # 2.2 如何为元组中的每个元素命名, 提高程序可读性 # NAME = 0 # AGE = 1 # SEX = 2 # EMAIL =3 NAME,AGE,SEX,EMAIL = xrange(4) student = (‘jimi‘,16,‘role‘,‘[email protected]‘) print student[NAME] # 2 命名的元祖 from collections import namedtuple Student = namedtuple(‘Student‘,[‘name‘,‘age‘,‘sex‘,‘email‘]) s = Student(‘jimi‘,16,‘role‘,‘[email protected]‘) s.age s.name s.email
时间: 2024-12-16 12:31:03