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

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

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

使用列表推导,只保留元素个数等于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) == ...

使用列表推导,只保留元素个数等于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) == ...

可以对第二个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]如果每一个列表中均没有重复的元素,那么...

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

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

使用list的index方法可以找到list中第一次出现该元素的位置 >>> l = ['a','b','c','c','d','c']>>> find='b'>>> l.index(find)1找出出现该元素的所有位置可以使用一个简单的表理解来实现 >>> find = 'c'>>> [i for i,v in enumerate(l) if v==fi...

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