Python 当列表有1时,唯一编号功能不起作用

Python 当列表有1时,唯一编号功能不起作用,python,python-3.6,Python,Python 3.6,我试图创建一个函数,在其中它从列表中删除重复项,但是 只要列表中有1,它就会失败。它适用于所有其他数字 我不确定是什么原因造成的。有一个包含一些数字的数组。 保证数组包含3个以上的数字 def find_uniq(arr): new_list = [] for i in arr: if i not in new_list: new_list.append(i) # this returns the second value in n

我试图创建一个函数,在其中它从列表中删除重复项,但是 只要列表中有
1
,它就会失败。它适用于所有其他数字 我不确定是什么原因造成的。有一个包含一些数字的数组。 保证数组包含3个以上的数字

def find_uniq(arr):
    new_list = []
    for i in arr:
        if i not in new_list:
            new_list.append(i)
    # this returns the second value in new_list as there are two values in the list.
    return new_list[1]

您不需要创建一个包含列表中所有唯一值的新列表。一旦检测到重复,只需返回另一个数字,因为它保证是唯一的

问题表明输入保证包含至少3个元素。您可以先检查前3个元素,查看其中是否有唯一的元素:

if input[0] != input[1]:
    if input[0] == input[2]:
        return input[1]
    else:
        return input[0]
elif input[1] != input[2]
    if input[0] == input[1]:
        return input[2]
    else:
        return input[0]
elif input[0] != input[2]
    if input[0] == input[1]:
        return input[2]
    else:
        return input[0]
如果你通过了,这意味着前3个元素是重复的。您可以简单地循环输入的其余部分,查找与此不相等的第一个元素

dup = input[0]
for el in input[3:]:
    if el != dup:
        return el

为什么最后返回
new\u list[1]
?new\u list最初返回两个值[a,b]。我要找的数字是b,所以我只显示第二个值。为什么
new\u list
只有两个值?它将具有与输入中唯一元素相同的值。请发布完整版本的代码。此外,不使用
列表(set(arr))
的任何原因?如果输入只有一个元素,那么
新列表中怎么可能有两个值?如果要返回最后一个唯一元素,请使用
new\u list[-1]