python library basic

一组python基本库的使用代码摘抄。

1
2
3
4
5
6
7
8
9
10
11
12
from collections import Counter
s = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower()
c = Counter(s)
# 获取出现频率最高的5个字符
print c.most_common(5)
# Result:
[(' ', 54), ('e', 32), ('s', 25), ('a', 24), ('t', 24)]

1
2
3
4
5
6
7
8
9
#zip函数,组装成dictionary
name=('jack','beginman','sony','pcky')
age=(2001,2003,2005,2000)
dict_name_key = dict(zip(name,age))
print(dict_name_key)
#zip函数,反转dictionary(将key与value反转)
dict_age_key = dict(zip(dict_name_key.values(), dict_name_key.keys()))
print(dict_age_key)
1
2
3
4
# revert a list
list = [1,2,3,4]
list[::-1] # -1 is stride. when it's -1, means reversing.
reversed(list) # this works too