繁体   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