案例式精讲python开发技巧

第二章 数据结构相关话题

1、如何在列表、字典、集合中根据条件筛选数据

  #列表
  from random import randint
  data = [randint(-10,10) for _ in range(10)]
  list(filter(lambda x :x >=0, data))
  [x for x in data if x >= 0] #更快一些
     
  #字典
  data1 = {x: randint(60,100) for x in range(1,20)}
  {k: v for k,v in data1.items() if v>=90}
    
  #集合
  data2 = set(data)
  {x for x in data2 if x % 3==0}

2、如何给元组中的每个元素命名,提高程序可读

student = ('Jim', 16, 'male', '[email protected]')

NAME, AGE, SEX, EMAIL = list(range(4))
print(student[NAME])#可读

from collections import namedtuple #返回内置元组的子类
Student = namedtuple('Student', {'name','age','sex','email'}) #类的工厂
s = Student('Jim', 16, 'male', '[email protected]')
print(s.name) #直接用类对象形式访问元组
print(isinstance(s,tuple)) #true

3、如何统计上出序列中元素的出现频度

#统计字典的频数
from random import randint
d = [randint(0,20) for _ in range(30)]
c = dict.fromkeys(d, 0)#data作为键
for i in d:
    c[i] += 1

#sorted函数返回一个list,a = sorted(c)

from collections import Counter
c2 = Counter(d)
c2.most_common(3)

#统计英文词频
import re
txt = open(r'C:\Users\Windows\Desktop\word_count.txt').read()
word = re.split('\W+', txt)#以非字母的正则表达式来进行分割
c3 = Counter(word)
c3.most_common(10)

4、如何根据字典中值的大小,对字典的项进行排序

from random import randint
d = {x:randint(60,,10)for x in 'xyzabc'}
sorted(d)#对键比较
#利用zip将字典数据转化为元组
sorted(zip(d.values(), d.keys()))

#利用sorted的key参数
sorted(d.items(), key=lambda x :x[1], reverse=True)

#利用operator
import operator
sorted(d.items(), key=operator.itemgetter(1))

5、公共键(快速在多个字典里寻找)

from random import randint, sample
d = [{i: randint(1,4) for i in sample('abcdefgh', randint(3,6))} for _ in range(5)]
s1 = {i: randint(1,4) for i in sample('abcdefgh', randint(3,6))}
s2 = {i: randint(1,4) for i in sample('abcdefgh', randint(3,6))}
s3 = {i: randint(1,4) for i in sample('abcdefgh', randint(3,6))}
#常用方式
res = []
for k in s1:
    if k in s2 and k in s3:
        res.append(k)

#map得到所有键的集合,reduce函数迭代
list(map(dict.keys,[s1, s2, s3]))
from functools import reduce
reduce(lambda a, b: a & b, list(map(dict.keys, [s1, s2, s3])))

6、如何让字典有序

# orderedDict()
from collections import orderedDict
from random import randint
from time import time
start = time()
#d = {}无序
d = orderedDict()
players = 'abcdefgh'
for i in range(len(players)):
    input()
    index = players.pop(randint(0, len(players) - i)
    d[index] = (i+1, end-start)
    end = time()
    print(i+1, index, end-start)

print('~'*20)
for i in d:
    print(i, ':', d[i])

7、如何实现用户的历史记录功能

# deque
from collections import deque
from random import randint
import pickle
import os
queue = deque([], 5) # 第一个值为初始值,第二个为大小


def guess(item):
    if item == target:
        print('Bingo!')
        return True
    if item < target:
        print('less than target')
    elif item > target:
        print('greater than target')
    return False

if os.path.exists('history'):
    pickle.load(open(r'D:\PythonWork\working_study\history', 'rb'))

target = randint(1, 100)
print(target)
while True:
    string = input('please input a number(1-100):')
    if string == '?' or string == '0':
        print(queue)
    elif string.isdigit():
        data = int(string)
        queue.append(data)
        if guess(data):
            pickle.dump(queue, open(r'D:\PythonWork\working_study\history', 'wb'))
            break

if os.path.exists('history'):
    his = pickle.load(open(r'D:\PythonWork\working_study\history', 'rb'))
    print(his)

第三章 迭代器与生成器相关话题

1、如何实现可迭代对象和迭代器对象

# Iterator, Iterable
import requests

def weather(city):
    r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)
    data = r.json()['data']['forecast'][1]
    print(('日期: %s, 高温: %s, 天气: %s') % (data['date'], data['high'], data['type']))


weather('武汉')
weather('北京')


from collections import Iterable, Iterator

class WeatherIterator(Iterator):
    def __init__(self, city_list):
        self.city_list = city_list
        self.index = 0

    def get_weather(self, city):
        r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)
        data = r.json()['data']['forecast'][1]
        print(('日期: %s, 高温: %s, 天气: %s') % (data['date'], data['high'], data['type']))
        return '%s, %s, %s' % (city, data['low'], data['high'])

    def next(self):
        if self.index == len(self.city_list):
            raise StopIteration
        city = self.city_list[self.index]
        self.index += 1
        return self.get_weather(city)


class WeatherIterable(Iterable):
    def __init__(self, cities):
        self.cities = cities

    def __iter__(self):
        # 返回迭代器的一个实例
        return WeatherIterator(self.cities)

cities = ['武汉', '北京', '上海', '广州', '深圳', '成都', '重庆', '厦门', '香港']
for x in WeatherIterable(cities):
    print(x)

第四章 字符串处理相关话题

1、如何拆分含有多种分隔符的字符串

1

你可能感兴趣的:(案例式精讲python开发技巧)