Python列表操作:列表去重以及列表列表各元素计数

1.列表各元素计数问题:

count()可以返回指定元素在列表中出现的次数。

1 >>> a = [10,20,30,40,50,20,30,20]
2       
3 >>> a.count(20)
4       
5 3

 

2.列表去重:

开发中对数组、列表去重是非常常见的需求,对一个list中的id进行去重,有下面几种方法,前面两种方法不能保证顺序, 后面两种方法可以保持原来的顺序。

下面的代码都在Python3下测试通过, Python2下请自行测试

1. 使用set的特型,python的set和其他语言类似, 是一个无序不重复元素集

orgList = [1,0,3,7,7,5]
#list()方法是把字符串str或元组转成数组
formatList = list(set(orgList))
print (formatList)

结果:

[0, 1, 3, 5, 7]

 

2. 使用keys()方法

orgList = [1,0,3,7,7,5]
#list()方法是把字符串str或元组转成数组
formatList = list({}.fromkeys(orgList).keys())
print (formatList)

结果:

[0, 1, 3, 5, 7]

 

上面两种方法的问题是:结果是没有保持原来的顺序。

 

3. 循环遍历法

orgList = [1,0,3,7,7,5]
formatList = []
for id in orgList:
    if id not in formatList:
        formatList.append(id)
print (formatList)

结果:

[1, 0, 3, 7, 5]

but,这样的代码不够简洁,不够高端

 

4. 按照索引再次排序

orgList = [1,0,3,7,7,5]
formatList = list(set(orgList))
formatList.sort(key=orgList.index)
print (formatList)

结果:

[1, 0, 3, 7, 5]

原文来源:https://m.pythontab.com/article/1194

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值