简体   繁体   中英

to find the distinct element in a list of identical values in python

I have a python list containing n elements, out of which n-1 are identical and 1 is not. I need to find the position of the distinct element.

For ex : Consider a python list [1,1,1,2,1,1] . I need the to find out the position of 2 in the list.

I can use a for loop to compare consecutive elements and then use two more for loops to compare those elements with the other elements. But is there a more efficient way to go about it or perhaps a built-in function which I am unaware of?

Make a set out of it, then count those set elements' occurrences in the list and find the unique element's index() in it.

l = [1,1,1,2,1,1]
a,b = set(l)
if l.count(a) == 1:
    unique = l.index(a)
else:
    unique = l.index(b)

Result:

>>> unique
3

You could use Counter, for example:

from collections import Counter

a = [1, 1, 1, 1, 2, 3, 3, 1, 1]
c = Counter(a)
for item, count in c.iteritems():
    if count == 1:
        print a.index(item)

This would print out 4, the index of 2 in the list a

Here's a slightly more efficient way (only goes through the list once instead of three times as in TigerhawkT3's answer ), but not quite as clean:

def find_distinct_index(a):
    if len(a) < 3: raise ValueError("Too short of a list")
    if a[0] == a[1]:
        # it's neither the first nor the second element, so return
        # the index of the leftmost element that is *not* equal to 
        # the first element
        for i, el in enumerate(a):
            if el != a[0]: return i
        raise ValueError("List had no distinct elements")
    else:
        # it's either the first or the second. use the third to figure
        # out which to return
        return a[1] if a[0] == a[2] else a[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM