简体   繁体   English

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

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

I have a python list containing n elements, out of which n-1 are identical and 1 is not. 我有一个包含n个元素的python列表,其中n-1个相同,而1个不相同。 I need to find the position of the distinct element. 我需要找到不同元素的位置。

For ex : Consider a python list [1,1,1,2,1,1] . 例如:考虑一个python列表[1,1,1,2,1,1] I need the to find out the position of 2 in the list. 我需要找出2在列表中的位置。

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. 我可以使用for循环比较连续的元素,然后再使用两个for循环将那些元素与其他元素进行比较。 But is there a more efficient way to go about it or perhaps a built-in function which I am unaware of? 但是,有没有更有效的方法来解决这个问题,或者也许是我不知道的内置函数?

Make a set out of it, then count those set elements' occurrences in the list and find the unique element's index() in it. 从中建立一个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)

Result: 结果:

>>> unique
3

You could use Counter, for example: 您可以使用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)

This would print out 4, the index of 2 in the list a 这将打印出4,列表a中的索引2

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: 这是一种稍微有效的方法(仅遍历该列表一次,而不是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