python中Counter(), join(), items(), index()函数的用法

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)]) <class 'dict_items'>

可结合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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值