我有一個包含n個元素的Python列表,其中n-1是相同的,而1不是。我需要找到獨特元素的位置。在Python中找到相同值的列表中的獨特元素
例如:考慮python列表[1,1,1,2,1,1]
。 我需要在列表中找出2的位置。
我可以使用for循環來比較連續的元素,然後使用兩個for循環來比較這些元素與其他元素。但是有沒有一種更有效的方法去實現它,或者是一種我不知道的內置函數?
我有一個包含n個元素的Python列表,其中n-1是相同的,而1不是。我需要找到獨特元素的位置。在Python中找到相同值的列表中的獨特元素
例如:考慮python列表[1,1,1,2,1,1]
。 我需要在列表中找出2的位置。
我可以使用for循環來比較連續的元素,然後使用兩個for循環來比較這些元素與其他元素。但是有沒有一種更有效的方法去實現它,或者是一種我不知道的內置函數?
將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
可以縮寫爲:'a,b = set(l); unique = l.index(a如果l.count(a)== 1 else b)' – Claudiu
或'...(a如果l.count(a) - 1 else b)',但我沒有打高爾夫球。 :) – TigerhawkT3
這裏有一個稍微更有效的方式(只有通過這樣的例子不勝枚舉一次而不是三次爲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]
您可以使用計數器,例如:
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
一種方法是將數組的元素添加到集合(拒絕重複項)。該集合將包含恰好兩個元素。選擇其中一個並計算它在陣列中出現的次數。如果那== 1,你找到了它。否則,它的另一個。 – danh