繁体   English   中英

列表中的唯一列表

[英]Unique lists from a list

给定一个列表,我需要返回一个唯一项列表。 我想看看是否有比我提出的更多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]]
>>> 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]]

使用默认字典。

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

我发现函数set()的build很常用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM