一些小的语法笔记2

import heapq
heapq.nlargest(n,nums),nums可迭代,该函数返回前n个最大数
heapq.nsmallest(n,nums),nums可迭代,该函数返回最小的n个数
heapq.nlargest(n,nums,lambda s:s['xxx']),nums可迭代,设每个迭代对象是s,以s['xxx']排序,取前n个最大数
heapq.nsmallest(n,nums,lambda s:s['xxx']),nums可迭代,设每个迭代对象是s,以s['xxx']排序,取最小的n个数
heapq.heapify(nums)和heapq.heappop(nums)同时使用,前者将nums转化为heap,后者就可以使用heap化的nums每次扔出一个最小值

In principle, constructing a multivalued dictionary is simple. However, initialization of the first value can be messy if you try to do it yourself. For example, you might have code that looks like this:

d = {}
for key, value in pairs:
    if key not in d:
         d[key] = []
    d[key].append(value)

Using a defaultdict simply leads to much cleaner code:

d = defaultdict(list)
for key, value in pairs:
    d[key].append(value)

To control the order of items in a dictionary, you can use an OrderedDict from the collections module.
An OrderedDict internally maintains a doubly linked list that orders the keys according to insertion order.the size of an OrderedDict is more than twice as large as a normal dictionary due to the extra linked list that’s created.Thus, if you are going to build a data structure involving a large number of OrderedDict instances (e.g., reading 100,000 lines of a CSV file into a list of OrderedDict instances), you would need to study the requirements of your application to determine if the benefits of using an OrderedDict outweighed the extra memory overhead.

from collections import OrderedDict

d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4

# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
    print(key, d[key])

zip() solves the problem by “inverting” the dictionary into a sequence of (value, key) pairs. When performing comparisons on such tuples, the value element is compared first, followed by the key. This gives you exactly the behavior that you want and allows reductions and sorting to be easily performed on the dictionary contents using a single statement.

prices = {
   'ACME': 45.23,
   'AAPL': 612.78,
   'IBM': 205.55,
   'HPQ': 37.20,
   'FB': 10.75
}
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')

A dictionary is a mapping between a set of keys and values. The keys() method of a dictionary returns a keys-view object that exposes the keys. A little-known feature of keys views is that they also support common set operations such as unions, intersections, and differences. Thus, if you need to perform common set operations with dictionary keys, you can often just use the keys-view objects directly without first converting them into a set.
The items() method of a dictionary returns an items-view object consisting of (key, value) pairs. This object supports similar set operations and can be used to perform operations such as finding out which key-value pairs two dictionaries have in common.
Although similar, the values() method of a dictionary does not support the set operations described in this recipe. In part, this is due to the fact that unlike keys, the items contained in a values view aren’t guaranteed to be unique. This alone makes certain set operations of questionable utility.However, if you must perform such calculations, they can be accomplished by simply converting the values to a set first.

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

b = {
   'w' : 10,
   'x' : 11,
   'y' : 2
}
# Find keys in common
a.keys() & b.keys()   # { 'x', 'y' }

# Find keys in a that are not in b
a.keys() - b.keys()   # { 'z' }

# Find (key,value) pairs in common
a.items() & b.items() # { ('y', 2) }

# Make a new dictionary with certain keys removed
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
# c is {'x': 1, 'y': 2}

You want to eliminate the duplicate values in a sequence, but preserve the order of the remaining items.

def dedupe(items, key=None):
    seen = set()
    for item in items:
       #如果items可哈希,key=None。否则需要传入key函数。dict不可哈希
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)

python中的del用法比较特殊,新手学习往往产生误解,弄清del的用法,可以帮助深入理解python的内存方面的问题。

python的del不同于C的free和C++的delete。

由于python都是引用,而python有GC机制,所以,del语句作用在变量上,而不是数据对象上。

a=1       # 对象 1 被 变量a引用,对象1的引用计数器为1  
b=a       # 对象1 被变量b引用,对象1的引用计数器加1   
del a     #删除变量a,解除a对1的引用   
print(b)  #最终变量b仍然引用1  

del删除的是变量,而不是数据。

另外,关于list。

li=[1,2,3,4,5]  #列表本身不包含数据1,2,3,4,5,而是包含变量:li[0] li[1] li[2] li[3] li[4]   
first=li[0]     #拷贝列表,也不会有数据对象的复制,而是创建新的变量引用  
del li[0]  
print(li)      #输出[2, 3, 4, 5]  
print(first)   #输出 1  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值