簡體   English   中英

在Python中的相同值列表中找到不同的元素

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

我有一個包含n個元素的python列表,其中n-1個相同,而1個不相同。 我需要找到不同元素的位置。

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

我可以使用for循環比較連續的元素,然后再使用兩個for循環將那些元素與其他元素進行比較。 但是,有沒有更有效的方法來解決這個問題,或者也許是我不知道的內置函數?

從中建立一個set ,然后計算list這些set元素的出現次數,並在其中找到唯一元素的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

您可以使用Counter,例如:

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,列表a中的索引2

這是一種稍微有效的方法(僅遍歷該列表一次,而不是TigerhawkT3的答案中的三遍 ),但是卻不太干凈:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM