首页 > 解决方案 > 列表从 Python 中的另一个列表返回唯一值

问题描述

我需要创建一个新列表,其中包含另一个列表中的唯一值,还必须保持顺序。我的代码:

def unique_elements(a):
    newlist = []
    for i in range(len(a)):
        if a[i] not in a[i+1:] and a[i-1::-1] :
                newlist.append(a[i])
    return newlist

输出是:

unique_elements([1,2,2,3,4,3])
[1, 2, 4, 3]

我得到了半正确的结果,因为这个顺序没有得到维护。正确的输出应该是:

[1,2,3,4]

有人可以让我知道我哪里出错了。

我从其他帖子中得到了这个解决方案:

def unique_elements(a):
    newlist = []
    for i in a:
        if i not in newlist:
                newlist.append(i)
    return newlist

另外,我还没有接触过 Python 中的 SET。那么有人可以让我知道我的原始代码是否可以工作吗?

标签: pythonfor-loopif-statement

解决方案


尝试这个

def unique_elements(a):
    newlist = []
    for i in a:
        if i not in newlist:
            newlist.append(i)
    return newlist


xyz = [1,1,2,4,6,2,2,4,5]

print(unique_elements(xyz))

输出:

[1, 2, 4, 6, 5]

推荐阅读