Counter(), join(), items(), index()函数的用法
Counter(), join(), items(), index()函数的用法 Counter()(1)需要从Collections集合模块中引入集合类Counter。
from collections import Counter
(2)Counter(a)以字典的形式打印出数组a中每个元素出现的次数。
a = [1,4,2,3,2,3,4,2]
from collections import Counter
print Counter(a)
运行结果:
Counter({2: 3, 3: 2, 4: 2, 1: 1})
(3)Counter(a).most_common(n)可以打印出数组中出现次数最多的元素。参数n表示的含义是:输出几个出现次数最多的元素。
a = [1,4,2,3,2,3,4,2]
from collections import Counter
print Counter(a).most_common(2)
运行结果:
[(2, 3), (3, 2)]
‘’.jion()
连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串。
a=['1','2','3','4','5']
print(' '.join(a))
print('##'.join(a))
运行结果:
1 2 3 4 5
1##2##3##4##5
items()
字典(Dictionary).items() 函数以列表形式返回可遍历的(键, 值) 元组数组。
d = {'one': 1, 'two': 2, 'three': 3}
t=d.items()
print(t,type(t))
运行结果:
dict_items([('one', 1), ('two', 2), ('three', 3)])
可结合for循环使用
d = {'one': 1, 'two': 2, 'three': 3}
for key,value in d.items():
print(key + ':' + str(value))
运行结果:
one:1
two:2
three:3
当循环参数只有一个时
d = {'one': 1, 'two': 2, 'three': 3}
for i in d.items():
print(i)
运行结果:
('one', 1)
('two', 2)
('three', 3)
index()
用于从列表或元组中找出某个值第一个匹配项的索引位置。
a = [1,2,3,2,3,4,2]
print (a.index(2))
运行结果:
1