python列表的去重
Posted yangshier
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python列表的去重相关的知识,希望对你有一定的参考价值。
#需求:#对列表去重:lis = [2,3,5,3,2,4,8,5,6,7,5](目前为三种方法,持续更新。。。。方法思路来源于https://www.cnblogs.com/nyist-xsk/p/7473236.html,感谢了解去重之后解决了一个问题)
lis = [2,3,5,3,2,4,8,5,6,7,5] #方法一:使用set() 集合,这种方法利用set() 集合的去重。出来的结果是进行升序排好的 lis1 = list(set(lis)) print(lis1) #方法二:使用for循环和not in判断 该方法获取到的列表跟之前的顺序是相同的 lis2 = [] for i in lis: if i not in lis2: lis2.append(i) print(lis2) #方法三:使用类itertools中groupby() 的方法 该方法需要先进行排序(根据排序的规则最后输出的结果就是) import itertools lis = [2,3,5,3,2,4,8,5,6,7,5] lis2 = [] lis.sort() #不设置reverse=True 默认是升序,设置是降序,这一步是必须的 lis1 = itertools.groupby(lis) for k,v in lis1: lis2.append(k) print(lis2)#[2, 3, 4, 5, 6, 7, 8]升序
#其他方法之后更新
感谢https://www.cnblogs.com/nyist-xsk/p/7473236.html作者提供的思路解决了下面的问题。
#需求:对lis = [2,3,5,3,2,4,8,5,6,7,5]计算元素出现的次数。
lis = [2,3,5,3,2,4,8,5,6,7,5] #去重 lis1 = list(set(lis)) dic = {} for i in lis1: dic[i] = lis.count(i) #计数 print(dic)
#需求如下:给出一个购物车列表,对列表进行计数输出结果
"""
goods = [{"name": "电脑", "price": 1999},
{"name": "罗技鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
{"name": "罗技鼠标", "price": 20},
{"name":"电脑","price":1999},
{"name": "电脑", "price": 2999}]
#输出结果:
new_goods = [{"name":"电脑","price":1999,"count":2},
{"name": "罗技鼠标", "price": 10, "count": 1},
{"name": "罗技鼠标", "price": 20, "count": 1},
{"name": "美女", "price": 998,"count":1},
{"name": "游艇", "price": 20,"count":1},
{"name": "电脑", "price": 2999,"count":1}]
"""
goods = [{"name": "电脑", "price": 1999}, {"name": "罗技鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, {"name": "罗技鼠标", "price": 20}, {"name":"电脑","price":1999}, {"name": "电脑", "price": 2999}] #先进行去重 new_goods = [] for good in goods: if good not in new_goods: new_goods.append(good) #进行计数 for new_good in new_goods: new_good["count"] = goods.count(new_good) print(new_goods)
以上是关于python列表的去重的主要内容,如果未能解决你的问题,请参考以下文章