python3 cookbook 英文_python3-cookbook读书笔记(一)

第一章:数据结构和算法

1.1解压序列赋值给多个变量

即将N个元素的元组或者序列,赋值给N个变量

>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]

name, shares, price, (year, mon, day) = data

很简单,就不多说了

1.2解压可迭代对象赋值给多个变量

与1.1不同的地方在于,当可迭代对象的元素个数大于赋值的变量的时候的处理

给出的解决方案是用星号表达式来处理

>>> *trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]

>>> trailing

[10, 8, 7, 1, 9, 5, 10]

>>> current

3

1.3保留最后N个元素

主要是collections.deque的使用

使用 deque(maxlen=N) 构造函数会新建一个固定大小的队列。当新的元素加入并且这个队列已满的时候, 最老的元素会自动被移除掉

>>> q = deque(maxlen=3)

>>> q.append(1)

>>> q.append(2)

>>> q.append(3)

>>> q

deque([1, 2, 3], maxlen=3)

>>> q.append(4)

>>> q

deque([2, 3, 4], maxlen=3)

>>> q.append(5)

>>> q

deque([3, 4, 5], maxlen=3)

deque还提供了在队列两端添加和弹出操作

>>> q = deque()

>>> q.append(1)

>>> q.append(2)

>>> q.append(3)

>>> q

deque([1, 2, 3])

>>> q.appendleft(4)

>>> q

deque([4, 1, 2, 3])

>>> q.pop()

3

>>> q

deque([4, 1, 2])

>>> q.popleft()

4

队列的插入和删除元素时间复杂度是 o(1),而列表是o(n)

1.4从一个集合中获取最小或最大的N个元素

heapq 模块有两个函数:nlargest() 和 nsmallest() 可以完美解决这个问题

import heapq

nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]

print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]

print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]查找元素的个数相对集合个数较小的时候,用heaqp模块的nlargest()和nsmallest()比较好

当查找集合中唯一最大或最小的元素时,用max()和min()函数

当查找元素的个数和集合大小接近的时候,需要先排序然后再切片 处理(sorted(items)[-N:]或sorted(items)[N:])

还讨论了heapq关于堆数据结构的实现,使用nlargest() 和 nsmallest()函数时, 会先进行堆排序,然后取值

1.5实现一个有优先级的队列

heapq模块的heappush()和heappop()函数

import heapq

class 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]

push()会将一个元组放到队列中,优先级的实现也和这个元组有关

pop()函数调用heappop()函数,返回最小的元素。

如何界定最小的元素,是通过元组来实现的

>>> a = (1, 0, Item('foo'))

>>> b = (5, 1, Item('bar'))

>>> c = (1, 2, Item('grok'))

>>> a < b

True

>>> a < c

True

index是用来防止两个优先级相同时,做比较时如下报错时的解决方法

priority使用相反值的原因是因为heappop()函数返回的最小值,如果定义最高优先级的一个元素优先级为5,那么就需要他在堆里面最小,因此取相反数-5

>>> a = (1, Item('foo'))

>>> b = (5, Item('bar'))

>>> a < b

True

>>> c = (1, Item('grok'))

>>> a < c

Traceback (most recent call last):

File "", line 1, in

TypeError: unorderable types: Item() < Item()

使用方式

>>> class Item:

... def __init__(self, name):

... self.name = name

... def __repr__(self):

... return 'Item({!r})'.format(self.name)

...

>>> q = PriorityQueue()

>>> q.push(Item('foo'), 1)

>>> q.push(Item('bar'), 5)

>>> q.push(Item('spam'), 4)

>>> q.push(Item('grok'), 1)

>>> q.pop()

Item('bar')

>>> q.pop()

Item('spam')

>>> q.pop()

Item('foo')

>>> q.pop()

Item('grok')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python Cookbook英文版 Table of Contents Foreword Preface 1. Python Shortcuts 1.1 Swapping Values Without Using a Temporary Variable 1.2 Constructing a Dictionary Without Excessive Quoting 1.3 Getting a Value from a Dictionary 1.4 Adding an Entry to a Dictionary 1.5 Associating Multiple Values with Each Key in a Dictionary 1.6 Dispatching Using a Dictionary 1.7 Collecting a Bunch of Named Items 1.8 Finding the Intersection of Two Dictionaries 1.9 Assigning and Testing with One Statement 1.10 Using List Comprehensions Instead of map and filter 1.11 Unzipping Simple List-Like Objects 1.12 Flattening a Nested Sequence 1.13 Looping in Parallel over Index and Sequence Items 1.14 Looping Through Multiple Lists 1.15 Spanning a Range Defined by Floats 1.16 Transposing Two-Dimensional Arrays 1.17 Creating Lists of Lists Without Sharing References 2. Searching and Sorting 2.1 Sorting a Dictionary 2.2 Processing Selected Pairs of Structured Data Efficiently 2.3 Sorting While Guaranteeing Sort Stability 2.4 Sorting by One Field, Then by Another 2.5 Looking for Items in a Sorted Sequence Using Binary Search 2.6 Sorting a List of Objects by an Attribute of the Objects 2.7 Sorting by Item or by Attribute 2.8 Selecting Random Elements from a List Without Repetition 2.9 Performing Frequent Membership Tests on a Sequence 2.10 Finding the Deep Index of an Item in an Embedded Sequence 2.11 Showing Off Quicksort in Three Lines 2.12 Sorting Objects Using SQL's ORDER BY Syntax 3. Text 3.1 Processing a String One Character at a Time 3.2 Testing if an Object Is String-Like 3.3 Aligning Strings 3.4 Trimming Space from the Ends of a String 3.5 Combining Strings 3.6 Checking Whe

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值