列表中的唯一列表

时间:2012-03-30 04:01:00

标签: python

给定一个列表我需要返回一个唯一项列表。我想看看是否有比我提出的更多Pythonic方式:

def unique_lists(l):
    m = {}
    for x in l:
        m[x] = (m[x] if m.get(x) != None else []) + [x]
    return [x for x in m.values()]    

print(unique_lists([1,2,2,3,4,5,5,5,6,7,8,8,9]))

输出:

[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]

3 个答案:

答案 0 :(得分:9)

>>> L=[1,2,2,3,4,5,5,5,6,7,8,8,9]
>>> from collections import Counter
>>> [[k]*v for k,v in Counter(L).items()]
[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]

答案 1 :(得分:2)

使用默认字典。

>>> from collections import defaultdict
>>> b = defaultdict(list)
>>> a = [1,2,2,3,4,5,5,5,6,7,8,8,9]
>>> for x in a:
...     b[x].append(x)
...
>>> b.values()
[[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]

答案 2 :(得分:0)

我发现函数set()中的构建非常有用:

lst=[1,2,2,3,4,5,5,5,6,7,8,8,9]

def all_eq_elms(lst, elm):
    while True:
        try:
            yield lst.pop(lst.index(elm))
        except:
            break

[[e for e in all_eq_elms(lst,elm)] for elm in set(lst)]

Out[43]: [[1], [2, 2], [3], [4], [5, 5, 5], [6], [7], [8, 8], [9]]