如何在python中找到列表中的唯一元素?(不使用套装)

Kar*_*kar 2 python python-2.7 python-3.x

编写一个接受输入列表的函数,并返回一个仅包含唯一元素的新列表(元素只应在列表中出现一次,并且元素的顺序必须保留为原始列表.).

def unique_elements (list):
    new_list = []
    length = len(list)
    i = 0
    while (length != 0):
        if (list[i] != list [i + 1]):
            new_list.append(list[i])
        i = i + 1
        length = length - 1
    '''new_list = set(list)'''
    return (new_list)

#Main program
n = int(input("Enter length of the list: "))
list = []
for i in range (0, n):
    item = int(input("Enter only integer values: "))
    list.append(item)
print ("This is your list: ", list)
result = unique_elements (list)
print (result)
Run Code Online (Sandbox Code Playgroud)

我遇到了这个错误:

IndexError:列表索引超出范围

Joe*_*oka 16

这是最简单的方法:

a = [1, 2, 2, 3]
b = []
for i in a:
    if i not in b:
        b.append(i)
print (b)
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)