0

please help me, i want to write a function that takes a list as an argument and returns a new list of elements that appear more than once from the original list. I tried writing it this way but it doesn't give me the answer

def list(n):
    l = [ ]
    for s in n:
        if n.count(s) > 1:
            l.append(s)
        return l
    return None
4

4 回答 4

2

你可以使用filter()函数来做到这一点。这对于 CPU 来说不是最快的,但足够简洁和 Pythonic。

my_list = [1, 2, 2, 3, 4, 4, 5, 5, 6, 7]
print filter(lambda x: my_list.count(x) > 1, my_list)

演示#1

您也可以使用6502提到列表理解:

my_list = [1, 2, 2, 3, 4, 4, 5, 5, 6, 7]
print [x for x in my_list if my_list.count(x) > 1]

演示#2

于 2013-10-08T06:11:26.547 回答
2

你很近。您需要return从 for 循环中删除该语句。实际上,您在第一个元素之后无条件返回。

def list(n):
    l = []
    for s in n:
        if n.count(s) > 1:
           l.append(s)
    return l

其次,我强烈建议您不要使用list此函数的名称,因为这样会隐藏list非常有用的内置函数。

于 2013-10-08T06:11:56.850 回答
1
def list_duplicates(seq):
  seen = set()
  seen_add = seen.add
  #adds all elements it doesn't know yet to seen and all other to seen_twice
  seen_twice = set( x for x in seq if x in seen or seen_add(x) )
  # turn the set into a list (as requested)
  return list( seen_twice )

 a = [1,2,3,2,1,5,6,5,5,5]
 list_duplicates(a)

这将打印

[1,2,5]
于 2013-10-08T06:13:20.493 回答
0

我认为解决方案Eugene Naydenov很好,但我对其进行了一些增强:

In [1]: my_list = [1, 2, 2, 3, 4, 4, 5, 5, 6, 7];
In [2]: set_list = lambda(lst) : list(set(i for i in filter(lambda x: my_list.count(x) > 1, lst))) #set_list is function
In [3]: set_list(my_list)
Out[3]: [2, 4, 5]
于 2013-10-08T06:25:38.367 回答