博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python技能
阅读量:5119 次
发布时间:2019-06-13

本文共 5234 字,大约阅读时间需要 17 分钟。

dict设置默认值 “”      A common use of dictionaries is to count occurrences by setting    the value of d[key] to 1 on its first occurrence, then increment    the value on each subsequent occurrence.      This can be done several different ways,   but the get() method is the most succinct:     ”“”            d[key] = d.get(key, 0) + 1

 


 

 

sorted(d.iteritems(), key=lambda x: x[1] , reverse=reverse)
sorted(d.iteritems(), key=itemgetter(1), reverse=True) 用itemgetter比lambda快, iteritems比其他快
D = {
"serverA":{
"04-12":[12, 1333, 1232343], "04-15":[34, 15555, 343432], "04-13":[45, 44444, 45454]}, \ "serverB":{
"04-12":[12, 2333, 1232343], "04-15":[34, 35555, 343432], "04-13":[45, 34444, 45454]}, \ "serverC":{
"04-12":[12, 3333, 1232343], "04-15":[34, 25555, 343432], "04-13":[45, 24444, 45454]}, \ "serverD":{
"04-12":[12, 4333, 1232343], "04-15":[34, 45555, 243432], "04-13":[45, 14444, 45454]}, \ "serverE":{
"04-12":[12, 4333, 1232343], "04-15":[34, 45555, 343432], "04-13":[45, 14444, 45454]}, \ "serverF":{
"04-12":[12, 4333, 1232343], "04-15":[34, 45555, 143432], "04-13":[45, 14444, 45454]}, \ }

如果我们想按照 04-15日各个server的第二个数值(15555,35555,25555,45555)升序排序, 相同的话按第三个数值降序排

12345678910
>>> res = sorted(D.items(), key=lambda x: (x[1]["04-15"][1], -x[1]["04-15"][2]))>>> for item in res:>>>   print item>>>('serverA', {
'04-13': [45, 44444, 45454], '04-12': [12, 1333, 1232343], '04-15': [34, 15555, 343432]})('serverC', {
'04-13': [45, 24444, 45454], '04-12': [12, 3333, 1232343], '04-15': [34, 25555, 343432]})('serverB', {
'04-13': [45, 34444, 45454], '04-12': [12, 2333, 1232343], '04-15': [34, 35555, 343432]})('serverE', {
'04-13': [45, 14444, 45454], '04-12': [12, 4333, 1232343], '04-15': [34, 45555, 343432]})('serverD', {
'04-13': [45, 14444, 45454], '04-12': [12, 4333, 1232343], '04-15': [34, 45555, 243432]})('serverF', {
'04-13': [45, 14444, 45454], '04-12': [12, 4333, 1232343], '04-15': [34, 45555, 143432]})

 

 


 

 

file.close()  '''As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically close f when the with block is exited:'''from __future__ import with_statement # This isn't required in Python 2.6with open("hello.txt") as f:    for line in f:        print line, --------------------------------------------------------------------------- 'In older versions of Python, you would have needed to do this to get the same effect:'f = open("hello.txt")try:    for line in f:        print line,finally:    f.close()

 

Dictionary view objects

  The objects returned by ,  and are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.(与dict的keys,values和items方法(他们返回独立的list)的不同是viewobject会跟着dict动态变化)

Dictionary views can be iterated over to yield their respective data, and support membership tests:

>>> dishes = {
'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}>>> keys = dishes.viewkeys()>>> values = dishes.viewvalues()>>> # iteration>>> n = 0>>> for val in values:... n += val>>> print(n)504>>> # keys and values are iterated over in the same order>>> list(keys)['eggs', 'bacon', 'sausage', 'spam']>>> list(values)[2, 1, 1, 500]>>> # view objects are dynamic and reflect dict changes>>> del dishes['eggs']>>> del dishes['sausage']>>> list(keys)['spam', 'bacon']>>> # set operations>>> keys & {
'eggs', 'bacon', 'salad'}{
'bacon'}

 

del,remove,pop的区别

Use del to remove an element by index, pop() to remove it by index if you need the returned value, andremove() to delete an element by value. The latter requires searching the list, and raises ValueError if no such value occurs in the list.

When deleting index i from a list of n elements, the computational complexities of these methods are

del     O(n - i)pop     O(n - i)remove  O(n)

 


 

python 压测

Not only is del more easily understood, but it seems slightly faster than :

$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}""for k in d.keys():""  if k.startswith('f'):""    del d[k]"1000000 loops, best of 3:0.733 usec per loop$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}""for k in d.keys():""  if k.startswith('f'):""    d.pop(k)"1000000 loops, best of 3:0.742 usec per loop

Edit: thanks to Alex Martelli for providing instructions on how to do this benchmarking. Hopefully I have not slipped up anywhere.

First measure the time required for copying:

$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}""d1 = d.copy()"1000000 loops, best of 3:0.278 usec per loop

Benchmark on copied dict:

$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}""d1 = d.copy()""for k in d1.keys():""  if k.startswith('f'):""    del d1[k]"100000 loops, best of 3:1.95 usec per loop$ python -m timeit -s "d = {'f':1,'foo':2,'bar':3}""d1 = d.copy()""for k in d1.keys():""  if k.startswith('f'):""    d1.pop(k)"100000 loops, best of 3:2.15 usec per loop

Subtracting the cost of copying, we get 1.872 usec for pop() and 1.672 for del.

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/tangr206/archive/2013/04/16/3024472.html

你可能感兴趣的文章
Java再学习——关于ConcurrentHashMap
查看>>
如何处理Win10电脑黑屏后出现代码0xc0000225的错误?
查看>>
局域网内手机访问电脑网站注意几点
查看>>
[Serializable]的应用--注册码的生成,加密和验证
查看>>
Day19内容回顾
查看>>
第七次作业
查看>>
SpringBoot项目打包
查看>>
Linux操作系统 和 Windows操作系统 的区别
查看>>
《QQ欢乐斗地主》山寨版
查看>>
文件流的使用以及序列化和反序列化的方法使用
查看>>
Android-多线程AsyncTask
查看>>
第一个Spring冲刺周期团队进展报告
查看>>
红黑树 c++ 实现
查看>>
Android 获取网络链接类型
查看>>
linux中启动与终止lnmp的脚本
查看>>
gdb中信号的处理[转]
查看>>
LeetCode【709. 转换成小写字母】
查看>>
如何在Access2007中使用日期类型查询数据
查看>>
Jzoj4757 树上摩托
查看>>
CF992E Nastya and King-Shamans(线段树二分+思维)
查看>>