实际编程和面试都会遇到的典型问题。
如何在列表,字典,集合中根据条件筛选数据
from random import randintfrom timeit import timeitdata = [randint(-10,10) for _ in range(10)] filter(lambda x:x >= 0,data)#首选列表解析 时间比filter少一半左右[x for x in data if x >= 0]data = {x:randint(60,100) for x in range(1,21)}{k:v for k,v in data.items() if v > 90}data = set(data){x for x in data if x%3==0}复制代码
如何为元组中每个元素命名,提高程序的可读性
#第一种# NAME = 0# AGE = 1# SEX = 2# EMAIL = 3NAME,AGE,SEX,EMAIL = range(4)student = ('Jan',14,'male','jan@jan.net')#nameprint(student[NAME])#第二种from collections import namedtupleStudent = namedtuple('Student',['name','age','sex','email'])student= Student('Jan',14,'male','jan@jan.net')#nameprint(student[NAME])student.ageisinstance(student,tuple)复制代码
如何统计序列中元素的出现频度
from random import randintdata = [randint(1,10) for x in range(20)]c = dict.fromkeys(data,0)#第一种for x in data: c[x]+=1 #第二种from collections import Counterc2 = Counter(data)#出现频度最高的三个c2.most_common(3)#统计一篇文章中单词出现次数import re#导入Python之禅import thisc3 = Counter(re.split('\W+',this.s))复制代码
如何根据字典中值的大小,对字典中的项排序
from random import randintdata = {x:randint(60,100) for x in 'abcdefg'}#sorted(data.values())#第一种t = zip(data.values(),data.keys())sorted(t)#第二种sorted(data.items(),key=lambda x: x[1])复制代码
如何快速找到多个字典中的公共键(key)
from random import randint,samples1 = {x: randint(1,4) for x in sample('abcdefgh',randint(3,6))}s2 = {x: randint(1,4) for x in sample('abcdefgh',randint(3,6))}s3 = {x: randint(1,4) for x in sample('abcdefgh',randint(3,6))}#第一种res = []for k in s1: if k in s2 and k in s3: res.append(k) #第二种from functools import reduces1.keys()&s2.keys()&s3.keys()map(dict.keys,[s1,s2,s3])reduce(lambda a, b:a & b,map(dict.keys,[s1,s2,s3]))复制代码
如何让字典保持有序
d = {}d['Tom'] = (1,30)d['Linda'] = (1,40)d['Jack'] = (1,50)from collections import OrderedDictd = OrderedDict()d['Tom'] = (1,30)d['Linda'] = (1,40)d['Jack'] = (1,50)d.keys()from time import timefrom random import randintsorce = OrderedDict()players = list('abcdefgh')start = time()for i in range(8): input() p = players.pop(randint(0, 7 - i)) end = time() print(i+1,p,end - start) sorce[p] = (i+1,end - start)print('-'*20)for k in sorce: print(k,sorce[k])复制代码
如何实现用户的历史记录功能(最多n条)
from collections import dequefrom random import randintN = randint(0,100)# 一个容纳5个值的队列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 Falsewhile True: input_number = input('please input a number: ') if input_number.isdigit(): k = int(input_number) history.append(k) if guess(k): break elif input_number == 'history': print(list(history))复制代码