本文介绍了查找列表中出现多次的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 有更有效的方法吗? def f(L): ''''''返回一套在L.''''中出现多次的物品。 L =清单(L) 套装中的物品(L): L.remove(item) 返回集(L) |> f([0,0,1,1,2,2,3] ) set([0,1,2])Is there a more efficient way to do this?def f(L):''''''Return a set of the items that occur more than once in L.''''''L = list(L)for item in set(L):L.remove(item)return set(L)|>f([0, 0, 1, 1, 2, 2, 3])set([0, 1, 2])推荐答案 def f(L): D = dict() L $中的物品: 如果D中的项目: D [item] + = 1 else: D [item] = 1 返回[i for i,j in D.items()if j 1] 那将是我的方式,需要通过几个来测试它/> 千次迭代,看看哪一个最有效。def f(L):D = dict()for item in L:if item in D:D[item] += 1else:D[item] = 1return [i for i,j in D.items() if j 1]That would be my way to do it, would need to test it via severalthousand iterations to see which one is most efficient though. http:// aspn。 activestate.com/ASPN/Coo.../Recipe/502263 这是整齐的,但是因为列表而是二次时间。 remove()需要 a线性搜索。我们可以通过使用 删除集合而不是列表来创建一个有效的变体: def倍数(lst): 单身人士=套装(lst) mults = set() for x in lst: if x in singleles: singles.remove(x) else: mults.add(x) 返回mults 虽然可能更好的是: def倍数(lst): 见= set() mults = set() for x in lst: if x in see: mults.add(x) else: seen.add(x) 返回mults 我通常使用dicts来做这些事情,比如: def倍数(lst): h = {} for x in lst: h [x] = h.get(x,0)+ 1 返回集合([x代表h,如果h [x] 1则为x) - --BryanThat''s neat, but quadratic time because list.remove() requiresa linear search. We can make an efficient variant by usingremove on a set rather than a list:def multiples(lst):singles = set(lst)mults = set()for x in lst:if x in singles:singles.remove(x)else:mults.add(x)return multsThough probably better is:def multiples(lst):seen = set()mults = set()for x in lst:if x in seen:mults.add(x)else:seen.add(x)return multsI''ve typically used dicts for such things, as in:def multiples(lst):h = {}for x in lst:h[x] = h.get(x, 0) + 1return set([x for x in h if h[x] 1])----Bryan 这篇关于查找列表中出现多次的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!