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...

>>> re.sub("(.)\\1+", "\\1", "avvvcctaa")'avcta'

知道的有2中吧: #第一种oList = ['A',1,'B',2]iList = oList[:]oList.extend(iList)print oList#第二种oList = ['A',1,'B',2]nList = oList * 2print oList

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

参考如下: import copy a = [{'a':12,'b':21},{'a':13,'b':22},{'a':14,'b':22},{'a':15,'b':23},{'a':16,'b':22}] d = {} for i in a: d.setdefault(i['b'], 0) d[i['b']] += 1 at = copy.copy(a) for i in at: if d[i['b']] > 1: a.remove(i)...

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...

from itertools import chain, repeat from functools import partial, reduce this_is_a_list = [1, 2, 3, 4, 5] what_you_want = reduce( chain, map(list, map(partial(reduce, times=2), this_is_a_list))) this_is_a_list = [1, 2, 3, 4, 5...

可以对第二个list的元素进行遍历,检查是否出现在第二个list当中,如果使用表理解,可以使用一行代码完成任务。 list1 = [1,2,3,4,5]list2 = [4,5,6,7,8]print [l for l in list1 if l in list2]# [4,5]如果每一个列表中均没有重复的元素,那么...

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