Python技能

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)升序排序, 相同的话按第三个数值降序排

1
2
3
4
5
6
7
8
9
10
>>> 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.6

with 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 dict.viewkeys()dict.viewvalues() anddict.viewitems() 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 pop():

$ 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.

 

 

 

 

 

 

 

posted @ 2013-04-16 18:29  tangr206  阅读(291)  评论(0编辑  收藏  举报