2015-11-23 53 views
0

我有一个包含n个元素的Python列表,其中n-1是相同的,而1不是。我需要找到独特元素的位置。在Python中找到相同值的列表中的独特元素

例如:考虑python列表[1,1,1,2,1,1]。 我需要在列表中找出2的位置。

我可以使用for循环来比较连续的元素,然后使用两个for循环来比较这些元素与其他元素。但是有没有一种更有效的方法去实现它,或者是一种我不知道的内置函数?

+0

一种方法是将数组的元素添加到集合(拒绝重复项)。该集合将包含恰好两个元素。选择其中一个并计算它在阵列中出现的次数。如果那== 1,你找到了它。否则,它的另一个。 – danh

回答

1

set从中排除,然后将这些set元素的出现次数计入list中,并在其中找到唯一元素的index()

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) 

结果:

>>> unique 
3 
+0

可以缩写为:'a,b = set(l); unique = l.index(a如果l.count(a)== 1 else b)' – Claudiu

+0

或'...(a如果l.count(a) - 1 else b)',但我没有打高尔夫球。 :) – TigerhawkT3

0

这里有一个稍微更有效的方式(只有通过这样的例子不胜枚举一次而不是三次为TigerhawkT3's answer),但不是很干净:

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] 
1

您可以使用计数器,例如:

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) 

这将打印出4,列表中的索引2

相关问题