加载中…
正文 字体大小:

每天写点之-python collections

(2017-02-10 21:13:24)
标签:

python

分类: python

# -*- coding: utf-8 -*-
# @DATE : 2017/2/10 10:47
# @File : collection_usage.py

import collections

# counter 初始化
print(collections.Counter(["a", "b", "a", "b", "a", "c"]))
print(collections.Counter({"a": 2, "b": 3, "c": 1}))
print(collections.Counter(a=2, b=3, c=1))

c = collections.Counter()
print(c)
c.update("abababc")
print(c)
c.update({"a": 1, "d": 5})
print(c)

# counter access
c = collections.Counter("ababac")
for letter in "abcde":
print("{}: {}".format(letter, c[letter]))

# elements
c = collections.Counter("extremly")
print(c)
print(list(c.elements()))

# most common
c = collections.Counter()
with open("WordFilter.py", "r") as f:
for line in f:
c.update(line.strip().replace(" ", "").lower())

for letter, count in c.most_common(10):
print("{}: {}".format(letter, count))

# 数学运算
c1 = collections.Counter(["a", "b", "c", "a", "b", "b"])
c2 = collections.Counter("alphabet")

print(c1)
print(c2)
print(c1 + c2)
print(c1 - c2)
print(c1 & c2)
print(c1 | c2)


# ordered dict
d = {}
d["a"] = "A"
d["b"] = "B"
d["c"] = "C"
d["d"] = "D"
d["e"] = "E"
for k, v in d.items():
print("{}, {}".format(k, v))

print("Ordered Dict")
d = collections.OrderedDict()
d["a"] = "A"
d["b"] = "B"
d["c"] = "C"
d["d"] = "D"
d["e"] = "E"
for k, v in d.items():
print("{}, {}".format(k, v))




Counter({'a': 3, 'b': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter()
Counter({'a': 3, 'b': 3, 'c': 1})
Counter({'d': 5, 'a': 4, 'b': 3, 'c': 1})
a: 3
b: 2
c: 1
d: 0
e: 0
Counter({'e': 2, 'm': 1, 'l': 1, 'r': 1, 't': 1, 'y': 1, 'x': 1})
['e', 'e', 'm', 'l', 'r', 't', 'y', 'x']
e: 58
r: 56
t: 55
i: 48
o: 48
s: 48
d: 39
f: 36
n: 35
l: 33
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'a': 2, 'b': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})
Counter({'a': 4, 'b': 4, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})
Counter({'b': 2, 'c': 1})
Counter({'a': 2, 'b': 1})
Counter({'b': 3, 'a': 2, 'c': 1, 'e': 1, 'h': 1, 'l': 1, 'p': 1, 't': 1})
a, A
c, C
b, B
e, E
d, D
Ordered Dict
a, A
b, B
c, C
d, D
e, E

0

阅读 评论 收藏 转载 喜欢 打印举报
已投稿到:
  • 评论加载中,请稍候...
发评论

    发评论

    以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

      

    新浪BLOG意见反馈留言板 不良信息反馈 电话:4006900000 提示音后按1键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有