简体   繁体   English

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

[英]How to find unique elements in a list in python? (Without using set)

Write a function that accepts an input list and returns a new list which contains only the unique elements (Elements should only appear one time in the list and the order of the elements must be preserved as the original list. ).编写一个函数,它接受一个输入列表并返回一个仅包含唯一元素的新列表(元素在列表中只应出现一次,并且元素的顺序必须保留为原始列表。)。

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)

I am stuck with this error:我被这个错误困住了:

IndexError: list index out of range IndexError:列表索引超出范围

This is the simplest way to do it:这是最简单的方法:

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

The problem with your code is that you are looping length times but checking list[i] with list[i+1] , thus accessing an element past the end of the input list (eg in a list with 6 elements there are 6-1=5 pairs of consecutive elements).您的代码的问题在于您循环length时间,但检查list[i]list[i+1] ,从而访问超过输入列表末尾的元素(例如,在具有 6 个元素的列表中,有 6-1 = 5 对连续元素)。

A second issue with your code is that an input with only one element [1] should give as output [1] even if this element is not different from any other.您的代码的第二个问题是只有一个元素[1]的输入应该作为输出[1]给出,即使该元素与其他元素没有区别。 The input text means you should remove elements that are equal to other elements already present, not that you should keep elements that are different from the next one.输入文本意味着您应该删除与已经存在的其他元素相等的元素,而不是您应该保留与下一个不同的元素。

Another issue is that you're only checking for consecutive duplicates ie given the input list [1, 2, 1, 2] your logic wouldn't detect any duplication... looks like the exercise instead requires in this case as output of [1, 2] .另一个问题是,您只检查连续的重复项,即给定输入列表[1, 2, 1, 2]您的逻辑不会检测到任何重复...看起来练习在这种情况下需要作为[1, 2]

A trace for a simple algorithm to do this is执行此操作的简单算法的跟踪是

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

Note also that to check if an element is present in a list Python provides the in operator (eg if x in output: ... ) that can save you an explicit loop for that part.另请注意,要检查列表中是否存在元素,Python 提供了in运算符(例如if x in output: ... ),可以为该部分保存显式循环。

As a side note naming an input parameter list is considered bad practice in Python because list is the name of a predefined function and your parameter is hiding it.作为旁注,命名输入参数list在 Python list被认为是不好的做法,因为list是预定义函数的名称,而您的参数隐藏了它。

O(n) solution without using a set:不使用集合的 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]

One line implementation:一行实现:

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)

Prints:印刷:

[100, 3232, 57, 90]

The problematic line is > if (list[i] != list [i + 1]): < (6th line in your code).有问题的行是 > if (list[i] != list [i + 1]): < (代码中的第 6 行)。

Reason: Imagine your list has got 4 elements.原因:想象一下你的列表有 4 个元素。

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

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

In the last iteration 'i' will be 4 , so i + 1 will be 5.在最后一次迭代中 'i' 将是 4 ,所以 i + 1 将是 5。

There is no such 5th index in that list, because list indexes are counted from zero.该列表中没有这样的第 5 个索引,因为列表索引从零开始计数。

mylist[0] = 1我的列表[0] = 1

mylist[1] = 2我的列表[1] = 2

mylist[2] = 2我的列表[2] = 2

mylist[3] = 3我的列表[3] = 3

mylist[4] = No Index mylist[4] = 无索引

mylist[5] = No Index 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)
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)

Use of collections is best IMO, Accepted answer is simplest, Adding another approach using dict where you can check frequency as well,使用集合是最好的 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] 

You can also print by values based on requirements.您还可以根据要求按值打印。

You can work this out using sets and set comprehension syntax is in most cases overlooked.您可以使用集合来解决这个问题,并且在大多数情况下会忽略集合理解语法。 Just as lists sets can also be generated using comprehension.正如列表集也可以使用理解生成。

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

Found an easier approach for people on Python 3.7.在 Python 3.7 上为人们找到了一种更简单的方法

Using a dictionary :使用字典

list(dict.fromkeys(mylist))

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

相关问题 在列表中查找元素集而不用Python排序 - Find the set of elements in a list without sorting in Python 计算没有集合的列表中的唯一元素 - Count the unique elements in a list without set 是否有更快/优化的方法从 python 中的唯一元素集/列表中找到唯一组合 - Is there a faster/optimisable way to find unique combinations from a set/list of unique elements in python 在python中查找列表的唯一元素的索引? - Find the indexes of unique elements of a list in python? 在python列表中查找元组中的唯一元素 - Find unique elements in tuples in a python list 如何在 Python 中的字典列表中找到唯一的设置值 - How to find unique set values in the list of dictionaries in Python 如何使用python查找数组中的元素列表 - How to find a list of elements in an array using python python:在列表中查找升序/降序元素而不使用循环 - python:find a ascending/decreasing elements in a list without using loop 如何在不使用迭代器和蛮力的情况下在python中找到列表中元素的所有两位数组合 - How to find all the two digit combinations of the elements in a list in python without using iterators and brute force 如何在不使用集合的情况下在 Python 的两个字典值列表中找到公共元素? - How to find the common elements inside two list of values of dictionary in Python without using sets?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM