流畅的python学习笔记 持续更新

import array
numbers=array.array('h',[-2,-1,0,1,2])
#array.array(typecode,[initializer]) --typecode:元素类型代码;initializer:初始化器,若数组为空,则省略初始化器
memv=memoryview(numbers)
print(len(memv))
print(memv[0])
memv_oct=memv.cast('B')
print(memv_oct.tolist())#以列表形式查看内容
memv_oct[5]=4
print(numbers)
#因为我们把占 2 个字节的整数的高位字节改成了 4, 所以这个有符号整数的值就变成了 1024。

纸牌:

import collections
Card=collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
    ranks=[str(n) for n in range(2,11)]+list('JQKA')
    suits='spades diamonds clubs hearts'.split()
    def __init__(self):
        self._cards=[Card(rank,suit)for suit in self.suits
                                    for rank in self.ranks]
    def __len__(self):
        return len(self._cards)
    def __getitem__(self, position):
        return self._cards[position]

namedtuple,构建少数属性但没有方法的对象

以下是py自带编译器中的结果:

beer _card=Card('7','diamonds')
SyntaxError: invalid syntax
>>> beer_card=Card('7','diamonds')
>>> beer_card
Card(rank='7', suit='diamonds')
>>> deck=FrenchDeck()
>>> len(deck)
24
>>> deck[0]
Card(rank='2', suit='spades')
>>> 
=================== RESTART: C:\Users\gxy\Desktop\new 1.py ===================
>>> len(deck)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    len(deck)
NameError: name 'deck' is not defined
>>> deck=FrnchDeck()
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    deck=FrnchDeck()
NameError: name 'FrnchDeck' is not defined
>>> deck=FrenchDeck()
>>> len(deck)
52
>>> deck[-1]
Card(rank='A', suit='hearts')
>>> from random import choice
>>> choice(deck)
Card(rank='4', suit='spades')
>>> choice(deck)
Card(rank='2', suit='diamonds')
>>> choice(deck)
Card(rank='3', suit='hearts')
>>> deck[:3]
[Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')]
>>> deck[12::13]
[Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]
>>> for card in deck:
	print(card)

Card(rank='2', suit='spades')
Card(rank='3', suit='spades')
Card(rank='4', suit='spades')
Card(rank='5', suit='spades')
Card(rank='6', suit='spades')
Card(rank='7', suit='spades')
Card(rank='8', suit='spades')
Card(rank='9', suit='spades')
Card(rank='10', suit='spades')
Card(rank='J', suit='spades')
Card(rank='Q', suit='spades')
Card(rank='K', suit='spades')
Card(rank='A', suit='spades')
Card(rank='2', suit='diamonds')
Card(rank='3', suit='diamonds')
Card(rank='4', suit='diamonds')
Card(rank='5', suit='diamonds')
Card(rank='6', suit='diamonds')
Card(rank='7', suit='diamonds')
Card(rank='8', suit='diamonds')
Card(rank='9', suit='diamonds')
Card(rank='10', suit='diamonds')
Card(rank='J', suit='diamonds')
Card(rank='Q', suit='diamonds')
Card(rank='K', suit='diamonds')
Card(rank='A', suit='diamonds')
Card(rank='2', suit='clubs')
Card(rank='3', suit='clubs')
Card(rank='4', suit='clubs')
Card(rank='5', suit='clubs')
Card(rank='6', suit='clubs')
Card(rank='7', suit='clubs')
Card(rank='8', suit='clubs')
Card(rank='9', suit='clubs')
Card(rank='10', suit='clubs')
Card(rank='J', suit='clubs')
Card(rank='Q', suit='clubs')
Card(rank='K', suit='clubs')
Card(rank='A', suit='clubs')
Card(rank='2', suit='hearts')
Card(rank='3', suit='hearts')
Card(rank='4', suit='hearts')
Card(rank='5', suit='hearts')
Card(rank='6', suit='hearts')
Card(rank='7', suit='hearts')
Card(rank='8', suit='hearts')
Card(rank='9', suit='hearts')
Card(rank='10', suit='hearts')
Card(rank='J', suit='hearts')
Card(rank='Q', suit='hearts')
Card(rank='K', suit='hearts')
Card(rank='A', suit='hearts')
>>> for card in reversed(deck):
	print(card)

	
Card(rank='A', suit='hearts')
Card(rank='K', suit='hearts')
Card(rank='Q', suit='hearts')
Card(rank='J', suit='hearts')
Card(rank='10', suit='hearts')
Card(rank='9', suit='hearts')
Card(rank='8', suit='hearts')
Card(rank='7', suit='hearts')
Card(rank='6', suit='hearts')
Card(rank='5', suit='hearts')
Card(rank='4', suit='hearts')
Card(rank='3', suit='hearts')
Card(rank='2', suit='hearts')
Card(rank='A', suit='clubs')
Card(rank='K', suit='clubs')
Card(rank='Q', suit='clubs')
Card(rank='J', suit='clubs')
Card(rank='10', suit='clubs')
Card(rank='9', suit='clubs')
Card(rank='8', suit='clubs')
Card(rank='7', suit='clubs')
Card(rank='6', suit='clubs')
Card(rank='5', suit='clubs')
Card(rank='4', suit='clubs')
Card(rank='3', suit='clubs')
Card(rank='2', suit='clubs')
Card(rank='A', suit='diamonds')
Card(rank='K', suit='diamonds')
Card(rank='Q', suit='diamonds')
Card(rank='J', suit='diamonds')
Card(rank='10', suit='diamonds')
Card(rank='9', suit='diamonds')
Card(rank='8', suit='diamonds')
Card(rank='7', suit='diamonds')
Card(rank='6', suit='diamonds')
Card(rank='5', suit='diamonds')
Card(rank='4', suit='diamonds')
Card(rank='3', suit='diamonds')
Card(rank='2', suit='diamonds')
Card(rank='A', suit='spades')
Card(rank='K', suit='spades')
Card(rank='Q', suit='spades')
Card(rank='J', suit='spades')
Card(rank='10', suit='spades')
Card(rank='9', suit='spades')
Card(rank='8', suit='spades')
Card(rank='7', suit='spades')
Card(rank='6', suit='spades')
Card(rank='5', suit='spades')
Card(rank='4', suit='spades')
Card(rank='3', suit='spades')
Card(rank='2', suit='spades')
>>> 
#第二章 bisect 二分法搜索 *难点
import bisect
import sys
HAYSTACK=[1,4,5,6,8,12,15,20,21,23,23,26,29,30]
NEEDLES=[0,1,2,5,8,10,22,23,29,30,31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
    for needle in reversed(NEEDLES):
        position=bisect_fn(HAYSTACK,needle)
        offset=position*' |'
        print(ROW_FMT.format(needle,position,offset))
if __name__ =='__main__':
    if sys.argv[-1]=='left':
        bisect_fn=bisect.bisect_left
    else:
        bisect_fn=bisect.bisect
    print('DEMO:',bisect_fn.__name__)
    print('haystack ->',''.join('%2d'% n for n in HAYSTACK))
    demo(bisect_fn)

collections模块在内置的数据类型,比如:int、str、list、dict等基础之上额外提供了几种数据类型。

1.namedtuple(): 生成可以使用名字来访问元素内容的tuple子类
2.deque: 双端队列,可以快速的从另外一侧追加和推出对象
3.Counter: 计数器,主要用来计数
4.OrderedDict: 有序字典
5.defaultdict: 带有默认值的字典

双向队列

from collections import deque
dq=deque(range(10),maxlen=10)#可选参数,不可更改
print(dq)
dq.rotate(3)#队列旋转操作接受一个参数n,当n>0时,队列最右边n个元素移动到左边。反之,移动到右边
print(dq)
dq.rotate(-4)
print(dq)
dq.appendleft(-1)#长度已给定的队列尾部添加操作,头部会被删除
print(dq)
dq.extend([11,22,33])#尾部添加会挤掉前三个
print(dq)
dq.extendleft([10,20,30,40])#添加迭代器到双向队列,迭代器的元素会逆序出现在队列里
print(dq)


第二章小结

序列类型分为可变和不可变,序列切片

bisect.insort   bisect.bisect 不太懂

setdefault处理找不到的键

import sys
import re
WORD_RE=re.compile(r'\w+')
index={}
with open(sys.argv[0],encoding='utf-8')as fp:
    for line_no,line in enumerate(fp,1):
        for match in WORD_RE.finditer(line):
            word=match.group()
            column_no=match.start()+1
            location=(line_no,column_no)
            occurrences=index.get(word,[])#提取word出现的情况
            occurrences.append(location)#添加新单词的位置到列表
            index[word]=occurrences#把新的列表放进字典中
for word in sorted(index,key=str.upper):#sorted 函数的 key= 参数没有调用 str.uppper, 而是把这个方法的引用传递给sorted 函数, 这样在排序的时候, 单词会被规范成统一格式
    print(word,index[word])

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值