Reputation: 1676
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?
Upvotes: 0
Views: 142
Reputation: 7349
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
Upvotes: 1
Reputation: 229291
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]
Upvotes: 0
Reputation: 49320
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
Upvotes: 1