python常用函数 C

1. Counter(hashable) 直接使用统计可哈希元素每个元素的数量。

2. most_common:可以统计数量最多的n个元素。

1 from collections import Counter
2 
3 words = ['my', 'look', 'into', 'eyes', 'any', 'into', 'any', 'my', 'look', 'into', 'my', 'look', 'into', 'eyes', 'any']
4 wcount = Counter(words)
5 print(wcount)  # 结果 Counter({'into': 4, 'my': 3, 'look': 3, 'any': 3, 'eyes': 2})
6 
7 print(wcount.most_common(2))  # 结果 [('into', 4), ('my', 3)]

3. compress(iterable, callable) 根据序列去选择输出对应位置为 True 的元素。

1 def is_odd(n):
2     for i in n:
3         yield (i % 2 == 1)
4 
5 
6 ret = is_odd([1, 2, 3, 4, 5])
7 from itertools import compress
8 
9 print(list(compress([1, 2, 3, 4, 5], ret)))  # 结果 [1, 3, 5]

4. choice(iterable) random的choice方法可以随机进行选择

1 import random
2 
3 v = [1, 2, 'a', 'b', 4, 'f']
4 
5 print(random.choice(v))  # 返回单个元素 f
6 print(random.choices(v))  # 返回列表  [4]

5.  callable(object) callable是检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

1 def add(a, b):
2     return a + b
3 
4 print(callable(add))  # True
5 print(callable({'a': 1}))  # False

 

 
posted @ 2018-11-22 11:04  浅尝辄止易初心不改难  Views(153)  Comments(0Edit  收藏  举报