Py学习  »  Python

如何用清单理解实现python中的内置集

Sam D. • 5 年前 • 1507 次点击  

我如何实现 独特的 下面的函数和列表理解?我不想用内置的 设置 因为元素在集合中的顺序是任意的

def unique(list):
    u = []
    for e in list:
        if e not in u:
            u.append(e)
    return u
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38062
 
1507 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Sam D.
Reply   •   1 楼
Sam D.    6 年前

谢谢大家!

我试图实现它,如下所示:

def uniq(list):
    u = []
    d = [u.append(e) for e in list  if e not in u]
    return u

虽然它按预期工作,但在某种意义上它可能是一种糟糕的代码实践(我是Python的新手)。

U10-Forward
Reply   •   2 楼
U10-Forward    6 年前

一种简单的分类方法 set 按元素的索引是列表 l :

def unique(l):
    return list(sorted(set(l),key=l.index))
print(unique([1,2,3,3]))

输出:

[1, 2, 3]
blhsing
Reply   •   3 楼
blhsing    6 年前

如果使用的是python 3.6,则可以使用dict来模拟有序集:

def unique(l):
    return list(dict(zip(l, l)))
print(unique([3, 2, 4, 2]))

此输出:

[3, 2, 4]
cs95 Aditya Joshi
Reply   •   4 楼
cs95 Aditya Joshi    6 年前

您不能这样做,因为您需要在每次迭代时跟踪所看到的元素,这不是您可以用该语法做的事情。将列表与顺序统一的方法是使用 OrderedDict (或者只是用python3.7+听写)。

>>> from collections import OrderedDict
>>> [k for k in OrderedDict.fromkeys([1, 2, 1, 3])]
[1, 2, 3]

你实际上不需要理解清单。

>>> list(OrderedDict.fromkeys([1, 2, 1, 3]))
[1, 2, 3]