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

时间:2016-02-21 07:11:28

标签: 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)

我遇到了这个错误:

  

IndexError:列表索引超出范围

9 个答案:

答案 0 :(得分:16)

这是最简单的方法:

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

答案 1 :(得分:3)

您的代码存在的问题是您循环length次,但检查list[i] list[i+1],从而访问输入列表末尾的元素(例如,在列表中6个元素有6-1 = 5对连续元素。)

您的代码的第二个问题是,只有一个元素[1]的输入应该作为输出[1],即使此元素与其他元素没有区别。输入文本意味着您应该删除与已存在的其他元素相等的元素,而不是要保留与下一个元素不同的元素。

另一个问题是你只检查连续重复项,即如果输入列表[1, 2, 1, 2],你的逻辑将无法检测到任何重复...看起来这样的练习反而需要这种情况作为[1, 2]的输出。

执行此操作的简单算法的跟踪是

for each element in input
   if the element has not been included in output
       add the element to the end of output

另请注意,要检查列表中是否存在元素,Python会提供in运算符(例如if x in output: ...),可以为该部分保存显式循环。

作为附注,命名输入参数list在Python中被认为是不好的做法,因为list是预定义函数的名称,而您的参数正在隐藏它。

答案 2 :(得分:1)

O(n)解决方案,不使用集合:

>>> from collections import Counter, OrderedDict
>>> class OrderedCounter(Counter, OrderedDict):
...     pass
... 
>>> lst = [1, 2, 2, 3, 4, 5, 4]
>>> [x for x,c in OrderedCounter(lst).items() if c==1]
[1, 3, 5]

答案 3 :(得分:1)

有问题的行是> if(list [i]!= list [i + 1]):< (代码中的第6行)。

<强>原因: 想象一下,你的清单有4个元素。

例如:mylist = [1,2,2,3]。

mylist [i]!= mylist [i + 1]

在最后一次迭代中,'i'将为4,所以i + 1将为5。

该列表中没有第5个索引,因为列表索引从零开始计算。

mylist [0] = 1

mylist [1] = 2

mylist [2] = 2

mylist [3] = 3

mylist [4] =无索引

mylist [5] =无索引

    def unique_elements (list):
        new_list = []

   # Replace the while with a for loop** 

        for i in list:
          if i not in new_list:
            new_list.append(i)


        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)

答案 4 :(得分:0)

一行实施:

list = [100, 3232, 3232, 3232, 57, 57, 90]
new_list = []

[new_list.append(x) for x in list if x not in new_list]

print(new_list)

打印:

[100, 3232, 57, 90]

答案 5 :(得分:0)

l = [1, 2, 2, 3,4,5,6,5,7,8]
myList = []
[ myList.append(item) for item in l if item not in myList]
print(myList)

答案 6 :(得分:0)

使用集合是最好的 IMO, 接受的答案是最简单的, 使用 dict 添加另一种方法,您也可以在其中检查频率,


text = [100, 3232, 3232, 3232, 57, 57, 90]
# create empty dictionary
freq_dict = {}
 
# loop through text and count words
for word in text:
    # set the default value to 0
    freq_dict.setdefault(word, 0)
    # increment the value by 1
    freq_dict[word] += 1
 
unique_list = [key for key,value in freq_dict.items()]

print(unique_list )

print(freq_dict )
[100, 3232, 57, 90]
{100: 1, 3232: 3, 57: 2, 90: 1}

[Program finished] 

您也可以根据需求按值打印。

答案 7 :(得分:-1)

你可以使用集合来解决这个问题,并且在大多数情况下忽略了集合理解语法。正如列表集也可以使用理解生成。

elements = [1, 2, 3, 3, 5, 7, 8, 7, 9]
unique_elements = {element for element in elements}
print(unique_elements)

答案 8 :(得分:-1)

为使用 Python 3.7 的人找到了一个 easier approach

使用 a dictionary

list(dict.fromkeys(mylist))