Python Cookbook学习记录(一)

第一章:数据结构和算法

问题一:n个元素组成的元组或序列进行分解

方法一:利用n个元素赋值实现拆分 如:

p=(3,4,5,6)
a,b,c,d=p
print(a,b,c,d)

方法二:对列表或者元组进行遍历

p=(3,4,5,6)
for i in range(len(p)):
    print(p[i],end=''+" ")

列表中包含元组或者列表类似 进一步细分

data=['Anan',23,90,(2018,7,5)]
name,age,score,date=data
year,month,day=date
print(year,month,day)

一切可以迭代的都可以执行分解操作包括:字符串、文件、迭代器、生成器

问题二: 任意长度的迭代分解

方法一:利用*avrg实现

def drop_first_last(grade):
    first,*middle,last=grade
    print(sum([*middle])/len([*middle])) 
grade=[1,2,3,4,5,6]
drop_first_last(grade)
*trailing,current=[1,2,3,4,5,6,7,8]
print(*trailing)
print(current)

进行变长迭代案例

records=[
['foo',1,2],
['bar','hello'],
['foo',3,4]]

def do_foo(x,y):
    print('foo',x,y)
def do_bar(s):
    print('bar',s)

for tag,*args in records:
    if tag=='foo':
        do_foo(*args)
    elif tag=='bar':
        do_bar(*args)

问题三 队列的使用

from collections import deque

def search(lines,pattern,history=2):
    previous_lines=deque(maxlen=history)
    for line in lines:
        yield line,previous_lines
    previous_lines.append(line)
if __name__ == '__main__':
    with open('test.txt') as f:
        for line,previous in search(f,'zhen',2):
            for pline in previous:
                print(pline,end='')
            print(line,end='')
            # print('-'*20)

问题四:找出最大或最小的n个元素

import heapq
nums=(1,2,3,4,5,6,7,8)
print(heapq.nlargest(3,nums))  #[8, 7, 6]
print(heapq.nsmallest(3,nums))  #[1, 2, 3]

附录:\
附1

python sum求和函数使用

sum(iterable[, start])

iterable – 可迭代对象,如:列表、元组、集合。\
start – 指定相加的参数,如果没有设置这个值,默认为0。

案例:

sum([0,1,2])\
sum([0,1,2,3,4], 2)

http://www.runoob.com/python/python-func-sum.html

附2:

Python3:collections.deque的用法简介

from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry 入队
queue.append("Graham")          # Graham 入队
queue.popleft()                 # 队首元素出队
#输出: 'Eric'
queue.popleft()                 # 队首元素出队
#输出: 'John'
print(queue)                           # 队列中剩下的元素
#输出: deque(['Michael', 'Terry', 'Graham'])

具体使用:https://blog.csdn.net/yuehuanjue/article/details/39964965

d=deque([]) #创建一个空的双队列\
d.append(item) #在d的右边(末尾)添加项目item\
d.appendleft(item) #从d的左边(开始)添加项目item\
d.clear() #清空队列,也就是删除d中的所有项目\
d.extend(iterable) #在d的右边(末尾)添加iterable中的所有项目\
d.extendleft(item) #在d的左边(开始)添加item中的所有项目\
d.pop() #删除并返回d中的最后一个(最右边的)项目。如果d为空,则引发IndexError\
d.popleft() #删除并返回d中的第一个(最左边的)项目。如果d为空,则引发IndexError\
d.rotate(n=1) #将d向右旋转n步(如果n<0,则向左旋转)\
d.count(n) #在队列中统计元素的个数,n表示统计的元素\
d.remove(n) #从队列中删除指定的值\
d.reverse() #翻转队列

队列的使用和列表相似,但是队列比列表使用更优雅而且速度更快

问题五:实现优先级队列

实现一个队列,能够以给定的优先级对元素排序,每次pop操作师都返回优先级最高的那个元素

import heapq
class PriorityQueue(object):
    """docstring for PriorityQueue"""
    def __init__(self ):
        self._queue=[]
        self._index=0
    def push(self,item,priority):
        heapq.heappush(self._queue,(-priority,self._index,item))
        self._index+=1
    def pop(self):
        return heapq.heappop(self._queue)[-1]


class Item(object):
    def __init__(self,name):
        self.name=name

    def __repr__(self):
        return 'Item({})'.format(self.name)

q=PriorityQueue()
q.push(Item('foo'),1)
q.push(Item('anaen'),5)
q.push(Item('bar'),5)
q.push(Item('spam'),4)
q.push(Item('anan'),4)

print(q.pop())

在字典中将键映射到多个值上

d = {
'a' : [1, 2, 3],
'b' : [4, 5]
}
e = {
'a' : {1, 2, 3},
'b' : {4, 5}
}
print(d['a'])

初始化一键多值字典

from collections import defaultdict
d=defaultdict(list)
for key,value in paris:
    d[key].append(value)

问题九 在两个字典中寻找相同点

a={
    'x':1,
    'y':2,
    'z':3
}

b={
    'w':4,
    'x':1,
    'y':2
}


print(a.keys()&b.keys()) #{'y', 'x'}
print(a.keys()-b.keys()) #{'z'}
print(a.keys()|b.keys()) #{'w', 'z', 'y', 'x'}

第二章:字符串和文本

问题2.1 多分隔符的文本切割处理

import re
line = 'asdf fjdk; afed, fjek,asdf, foo'
a=re.split(r'[;,\s]\s*',line)
print(a) #['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']

通过re.split可以对任意分隔符进行分割

问题2.2 在字符串的开头或结尾做文本匹配


filename='file2.txt'
print(filename.startswith('file2.'))  #True
print(filename.endswith('txt')) #True

未完待续…

猜你喜欢

转载自blog.csdn.net/sinat_34789167/article/details/81129092