# 加载中...

bicloud
• 博客等级：
• 博客积分：0
• 博客访问：350,255
• 关注人气：487
• 获赠金笔：0支
• 赠出金笔：0支
• 荣誉徽章：

## 每天写点之-python collections

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

### python

```
# -*- coding: utf-8 -*-# @DATE    : 2017/2/10 10:47# @File    : collection_usage.pyimport 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 accessc = collections.Counter("ababac")
for letter in "abcde":    print("{}: {}".format(letter, c[letter]))

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

# most commonc = 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 dictd = {}
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键（按当地市话标准计费）　欢迎批评指正

新浪公司 版权所有