tnjk.net
当前位置:首页 >> python中list去重 >>

python中list去重

通过set来去重 >>> l = [1,2,3,4,5,2,1,3,45,3,21,12,4]>>> set(l)set([1, 2, 3, 4, 5, 12, 45, 21])>>> print list(set(l))[1, 2, 3, 4, 5, 12, 45, 21]>>>

使用列表推导,只保留元素个数等于1的 a = ['a', 'b', 'c', 'd', 'a', 'a']b = [x for x in a if a.count(x) == 1]print b 列表推导中的x for x in a if a.count(1) == 1和下面的for循环等价,不过更简洁: b = []for x in a: if a.count(x) == ...

n = 10a = [1,2,3,4,5]b = a * nprint b#[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, # 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, # 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, # 1, 2, 3, 4, 5]c = []for i in a:for j in range(n...

list(set(l))

list里的元素是可以重复的 l = [1,1,2,2,3,3]

可以先统计list中每个数据的个数,用一个dict存储,然后遍历list,判断是否是最后一个,是的就从list中删除即可

用*运算符 [1,2,3]*3 结果 [1, 2, 3, 1, 2, 3, 1, 2, 3]

集合set set(...)

l = [1,1,2,2,2,3,3,3,3,5,6,4,6,4,5,5,5] d = {} for x in set(l): d[x] = l.count(x) print d

subl=[i for i in l if l.count(i)>1]Python 3.5.2 (default, Sep 30 2016, 01:32:24) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> l=[2,2,3,4,5,6,7,7,7,7...

网站首页 | 网站地图
All rights reserved Powered by www.tnjk.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com