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

b = {}for dic in [each.items() for each in a]: for key,value in dic: b[key] = value

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

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

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) print a 先...

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

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

用集合 alist = [3,1,3,5,6,7,8,9] blist = set(alist)

words = ['hello', 'exercise', 'with', 'words']def repeat_letter(words,index,num): return_worlds=[] for i in range(0,len(words)): if len(words[i]) > index[i]: word_list=list(words[i]) range_word=word_list[index[i]]*(num+1) word_...

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