1:在字点、列表、集合中根据条件筛选数据
过滤掉列表 data1 = [1,5,-3,-2,9,0,6] 中的负数,
筛选出字典 data2 = {'LIlei':'79','Jim':'88','Lucy':'92'} 中值高于90的项,
筛出集合 data3 = {77,89,32,20,153}中能背3整除的元素。
问题一的三种解法(列表解析式最快,filter其次,第一种最慢)
result = [] for i in data1: if i>=0: result.append(i) print(result)
result = filter(lambda x:x>=0,data)#python2中返回列表,python3中返回可迭代对象 for x in result: print(x,end=',')
from random import randint data =[randint(-10,10) for _ in range(10)] a = [x for x in data if x>=0] print(a)
问题二的解法
from random import randint data ={x : randint(60,100) for x in range(1,11)} print(data) a = {k:v for k,v in data.items() if v >= 90} print(a)
问题三的解法
from random import randint data =[randint(10,30) for _ in range(10)] print(data) a = set(data) print(a) b = {x for x in a if x % 3 == 0} print(b)
2 :如何为元组中的每个元素命名,提高程序可读性(枚举法定义变量作为索引坐标,)
student = ('jim',18,'male','[email protected]') name,age,sex,email = range(4) print(student[name]) print(student[age]) print(student[sex]) print(student[email])
from collections import namedtuple student = namedtuple('student',['name','age','sex','email']) s = student('jim',16,'male','[email protected]') print(s,s.name ,s.age,s.sex,s.email)
3:如何统计序列中元素的出现频度
随机序列[12,5,5,6,4,6,7,5...]中,找出出现次数最高的3个元素,它们出现次数是多少
某英文文章的单词,进行词频统计,找出出现次数最高的10个单词,它们出现次数是多少
问题一
import random data = [random.randint(0,10) for _ in range(50)] print(data) d = dict.fromkeys(data,0) #print(d) for x in data: d[x] += 1 print(d) c = sorted(d.items(),key=lambda x:x[1]) #lambda 是匿名函数,key是sorted(min,max都可以)的参数,告诉它按找第几个元素来排序 print(c) [9, 3, 8, 3, 10, 3, 1, 2, 4, 10, 2, 0, 4, 8, 1, 10, 8, 6, 7, 1, 2, 0, 6, 2, 9, 6, 2, 6, 4, 8, 2, 7, 4, 0, 3, 9, 0, 10, 4, 2, 0, 1, 9, 0, 2, 1, 9, 6, 4, 7] {9: 5, 3: 4, 8: 4, 10: 4, 1: 5, 2: 8, 4: 6, 0: 6, 6: 5, 7: 3} [(7, 3), (3, 4), (8, 4), (10, 4), (9, 5), (1, 5), (6, 5), (4, 6), (0, 6), (2, 8)]
from collections import Counter data = [9, 3, 8, 3, 10, 3, 1, 2, 4, 10, 2, 0, 4, 8, 1, 10, 8, 6, 7, 1, 2, 0, 6, 2, 9, 6, 2, 6, 4, 8, 2, 7, 4, 0, 3, 9, 0, 10, 4, 2, 0, 1, 9, 0, 2, 1, 9, 6, 4, 7] c = Counter(data) print(c) #x.most_common(n) x是Counter()对象,此方法得到频度最高的n个元素 print(c.most_common(3))
Counter({2: 8, 4: 6, 0: 6, 9: 5, 1: 5, 6: 5, 3: 4, 8: 4, 10: 4, 7: 3})[(2, 8), (4, 6), (0, 6)]
问题二
from collections import Counter import re txt = 'When people ask me what kind of job I want to work on in the future, my answer is definitely being a teacher. I can pass my knowledge to the students and make contribution to the society, what a great job. I also like to share new things with others, so I am so eager to search the world and collect the valuable information. In order to realize my dream, I must study hard. No matter what kind of difficulties I meet, I will never give up. The successful people’ experiences show me the importance of insistence, and I know I can make it some day.' txt_list = re.split('\W+',txt) print(txt_list) d = Counter(txt_list) print(d) print(d.most_common(5)) ['When', 'people', 'ask', 'me', 'what', 'kind', 'of', 'job', 'I', 'want', 'to', 'work', 'on', 'in', 'the', 'future', 'my', 'answer', 'is', 'definitely', 'being', 'a', 'teacher', 'I', 'can', 'pass', 'my', 'knowledge', 'to', 'the', 'students', 'and', 'make', 'contribution', 'to', 'the', 'society', 'what', 'a', 'great', 'job', 'I', 'also', 'like', 'to', 'share', 'new', 'things', 'with', 'others', 'so', 'I', 'am', 'so', 'eager', 'to', 'search', 'the', 'world', 'and', 'collect', 'the', 'valuable', 'information', 'In', 'order', 'to', 'realize', 'my', 'dream', 'I', 'must', 'study', 'hard', 'No', 'matter', 'what', 'kind', 'of', 'difficulties', 'I', 'meet', 'I', 'will', 'never', 'give', 'up', 'The', 'successful', 'people', 'experiences', 'show', 'me', 'the', 'importance', 'of', 'insistence', 'and', 'I', 'know', 'I', 'can', 'make', 'it', 'some', 'day', ''] Counter({'I': 9, 'to': 6, 'the': 6, 'what': 3, 'of': 3, 'my': 3, 'and': 3, 'people': 2, 'me': 2, 'kind': 2, 'job': 2, 'a': 2, 'can': 2, 'make': 2, 'so': 2, 'When': 1, 'ask': 1, 'want': 1, 'work': 1, 'on': 1, 'in': 1, 'future': 1, 'answer': 1, 'is': 1, 'definitely': 1, 'being': 1, 'teacher': 1, 'pass': 1, 'knowledge': 1, 'students': 1, 'contribution': 1, 'society': 1, 'great': 1, 'also': 1, 'like': 1, 'share': 1, 'new': 1, 'things': 1, 'with': 1, 'others': 1, 'am': 1, 'eager': 1, 'search': 1, 'world': 1, 'collect': 1, 'valuable': 1, 'information': 1, 'In': 1, 'order': 1, 'realize': 1, 'dream': 1, 'must': 1, 'study': 1, 'hard': 1, 'No': 1, 'matter': 1, 'difficulties': 1, 'meet': 1, 'will': 1, 'never': 1, 'give': 1, 'up': 1, 'The': 1, 'successful': 1, 'experiences': 1, 'show': 1, 'importance': 1, 'insistence': 1, 'know': 1, 'it': 1, 'some': 1, 'day': 1, '': 1}) [('I', 9), ('to', 6), ('the', 6), ('what', 3), ('of', 3)]
4:如何根据字点中值的大小,对字典进行排序
from random import randint data = {x:randint(60,100) for x in "abcdef"} # 构造随机成绩字典 # 方式一 print(sorted(zip(data.values(),data.keys()))) # 利用元组的比较 # 方式二 print(sorted(data.items(),key=lambda x:x[1])) # 利用key参数
5:如何找到多个字典中的公共键
方法一执行效率不算好,稍微啰嗦
import random a = random.sample('abcdefg',random.randint(3,6)) #进球的球员,sapmle是取样,有两个参数 print(a) #第s1,s2,s3轮:进球的人和进球数(随机1-4) s1 = {x:random.randint(1,4) for x in random.sample('abcdefg',random.randint(3,6))} s2 = {x:random.randint(1,4) for x in random.sample('abcdefg',random.randint(3,6))} s3 = {x:random.randint(1,4) for x in random.sample('abcdefg',random.randint(3,6))} print(s1,'\n',s2,'\n',s3) for k in s1: if k in s2 and k in s3: print(k,end=',') ['d', 'c', 'b', 'e'] {'g': 1, 'f': 4, 'd': 3, 'c': 3} {'d': 2, 'a': 2, 'g': 3, 'f': 2, 'c': 4, 'b': 2} {'e': 3, 'a': 3, 'f': 2, 'g': 4, 'd': 4} g,f,d,
方法二
a = s1.keys() #python3是dict.keys()方法
b = s2.keys()
c = s3.keys()
f = a & b & c #集合取交集,这是前三轮的,如果是前n轮,则如下所示
print(f)
map(function, iterable, ...)
函数会根据提供的函数对指定序列做映射。
第一个参数 function
以参数序列中的每一个元素调用function
函数,返回包含每次 function
函数返回值的新列表。
# 计算平方数 def square(x) : return x ** 2 map(square, [1,2,3,4,5]) # 使用 lambda 匿名函数 map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # [1, 4, 9, 16, 25] # 提供了两个列表,对相同位置的列表数据进行相加 map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) # [3, 7, 11, 15, 19]
reduce(function, iterable)
函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给
reduce
中的函数
function
(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用
function
函数运算,最后得到一个结果。
# 求和 reduce(lambda x, y: x+y, [1,2,3,4,5]) # 15
from random import randint, sample from functools import reduce # 随机产生abcdefg球员中的3-6个人随机进1-4个球 s1 = {x: randint(1, 4) for x in sample("abcdefg", randint(3, 6))} s2 = {x: randint(1, 4) for x in sample("abcdefg", randint(3, 6))} s3 = {x: randint(1, 4) for x in sample("abcdefg", randint(3, 6))} res = reduce(lambda a, b: a & b, map(dict.keys, [s1, s2, s3])) print(res)
6:如何让字典保持有序
from collections import OrderedDict d = OrderedDict() d['Jim'] = (1, 35) d['Leo'] = (2, 37) d['Bob'] = (3, 40) for k in d: print(k) OrderedDict([('Jim', (1, 35)), ('Leo', (2, 37)), ('Bob', (3, 40))]) Jim Leo Bob
import time from random import randint from collections import OrderedDict d = OrderedDict() players = list('ABCDEFGH') start = time.time()# 考试开始时间 for i in range(8):#在8个人中 input()# 等待输入表示每输入一次就有一个人比赛做完题目 person = players.pop(randint(0,7-i))#随机选择完成的人,从列表中删除 end =time.time()#完成的人的时间 print(i+1,person,end-start) #打印 名词,姓名,时间 d[person] = (i+1,end-start) #按 姓名:(名次,时间)传入OrderDict()的字典对象中 for k in d: print(k,d[k]) 1 B 1.9241104125976562 2 E 3.323190450668335 3 C 4.003229141235352 4 H 4.50725793838501 5 D 5.011286735534668 6 A 5.531316518783569 7 F 6.428367853164673 8 G 7.011401176452637 B (1, 1.9241104125976562) E (2, 3.323190450668335) C (3, 4.003229141235352) H (4, 4.50725793838501) D (5, 5.011286735534668) A (6, 5.531316518783569) F (7, 6.428367853164673) G (8, 7.011401176452637)
7:如何实现用户的历史记录功能(队列,pickle.dump(obj,file))
from random import randint N = randint(0, 100) def guess(k): if k == N: print 'right' return True if k < N: print '%s is less-than N' % k else: print '%s is greater-than N' % k return False while True: line = raw_input("please input a number: ") # 判断用户输入的数据是否为数字 if line.isdigit(): k = int(line) if guess(k): break
用户猜数字,一遍猜中的概论是很低很低的,所以用户猜数字要猜很多很多遍才可能猜中。在猜数字的过程中,由于用户猜的数字次数很多,以至于用户会忘记猜过的数字。因此,我们是有必要添加历史记录功能的。这里为了简化操作,只显示用户最近输入的5个数字。
那如何实现这一功能呢?我们可以使用容量为n的队列存储历史记录:
- 使用标准库collections中的deque,它是一个双端循环队列
- 程序退出前,可以使用pickle将队列对象存入文件,再次运行程序时将其导入
import pickle from random import randint from collections import deque N = randint(0, 100) history = deque([], 5) def guess(k): if k == N: print 'right' return True if k < N: print '%s is less-than N' % k else: print '%s is greater-than N' % k return False while True: try: # 导入用户猜数字的历史记录 history = pickle.load(open('history')) line = raw_input("please input a number: ") except: line = raw_input("please input a number: ") # 判断用户输入的数据是否为数字 if line.isdigit(): k = int(line) history.append(k) # 将用户历史记录保存至history文件中 pickle.dump(history, open('history', 'w')) if guess(k): break # 用户查看历史记录 elif line == 'history' or line == 'his?': print list(history)