python cookbook读书笔记

本文是阅读Python cookbook第三版的一些笔记。


1、 zip()产生的生成器只能使用一次。

如:

prices_and_names = zip(prices.values(), prices.keys())
print(min(prices_and_names)) # OK
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
正确使用:

min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')

此外,要达成上面的效果,即输出价格单价和名称,通过key=lambda k:price[k]无法实现。

zip完后是tuple进行max or min,默认比较第一个元素,若第一个元素相同,比较后续元素。


2、collections

defaultdict、OrderedDict、deque等


3、heapq 默认最小堆

nsmallest、nlargest  可以通过key对排序函数进行指定

heapify,_heapify_max 进行最小堆化,还能进行最大堆化


4、字典中,键值对的键是唯一的,重复赋值会将之前的覆盖


5、& - 做交集和差集

set(a.items()) & set(b.items())
set(a.items()) - set(b.items())

6、对列表去重,并且元素相对顺序不变。

def dedupe(items):
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

>>> a = [1, 5, 2, 1, 9, 1, 5, 10]
>>> list(dedupe(a))
[1, 5, 2, 9, 10]

以上只能用于传入参数中元素可hashable的情况下。


def dedupe(items, key=None):
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)
>>> a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]
>>> list(dedupe(a, key=lambda d: (d['x'],d['y'])))
[{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]
>>> list(dedupe(a, key=lambda d: d['x']))
[{'x': 1, 'y': 2}, {'x': 2, 'y': 4}]


生成器的作用:

The use of a generator function in this recipe reflects the fact that you might want the function to be
extremely general purpose—not necessarily tied directly to list processing. For example, if you want
to read a file, eliminating duplicate lines, you could simply do this:
with open(somefile,'r') as f:
    for line in dedupe(f):
        ...
The specification of a  key function mimics similar functionality in built-in functions such as
sorted() ,  min() , and  max() .

简单的去重,只需set(a)即可。





























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值