从python中的列表创建子列表

时间:2013-10-08 06:06:58

标签: python

请帮助我,我想编写一个以列表作为参数的函数,并返回一个从原始列表中出现多次的新元素列表。我试着用这种方式写它,但它没有给我答案

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

4 个答案:

答案 0 :(得分: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)

DEMO #1

此外,您可以使用list comprehension作为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]

DEMO #2

答案 1 :(得分:2)

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

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

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

答案 2 :(得分: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]

答案 3 :(得分: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]
相关问题