【问题标题】:How to efficiently find the odds one out in a list?如何有效地找到列表中的赔率?
【发布时间】:2014-03-28 00:44:29
【问题描述】:

假设我有一个类似的列表

>>> l = [-10,-10,-10,-20,-10,-10]

鉴于你不知道它是 -20,我想在一行或两行中找到 -20 的位置和数量。有什么想法吗?

【问题讨论】:

  • 您应该指定您使用的 Python 版本。下面的答案使用 Python 2.7 中引入的 Counter 还有一些位置使用 Python 2.6.6
  • 谢谢。您获得了反击优势 (:-)

标签: python list


【解决方案1】:

这将找到最不常见的元素:

>>> my_list = [-10,-10,-10,-20,-10,-10]
>>> from collections import Counter
>>> counter = Counter(my_list)
>>> min(counter, key=counter.get)
-20

要查找职位,您可以使用my_list.index(min(counter, key=counter.get))

请注意,这不适用于[1, 2, 9999, 3, 4] 等列表中的奇数,您可能想查看我的答案here 以了解此类情况。

【讨论】:

    【解决方案2】:
    print min(l,key=l.count)
    

    但它可能没那么快

    from collections import Counter
    from operator import itemgetter
    print min(Counter(l).items(), key = itemgetter(1))[0]
    

    可能会更快

    from itertools import takewhile
    print l[len(list(takewhile(lambda x:l.count(x) != 1,l)))]
    

    可能是最有效的方法......我不知道计数器应该也很快

    【讨论】:

      【解决方案3】:

      假设您要查找只出现一次的项目:

      >>> from collections import Counter
      >>> l = [-10,-10,-10,-20,-10,-10]
      >>> [i for i, n in Counter(l).iteritems() if n == 1]
      [-20]
      

      【讨论】:

        【解决方案4】:

        如果您使用的 Python 版本早于 2.7,则尚未安装 Counter。如果是这样的话,那么答案就在Get the key corresponding to the minimum value within a dictionary

        mydict = dict((elem, my_list.count(elem)) for elem in my_list)
        mymin = min(mydict, key=mydict.get)
        
        print mydict
        print mymin
        

        输出:

        {-20:1, -10:5}
        -20
        

        【讨论】:

          猜你喜欢
          • 2021-04-15
          • 1970-01-01
          • 1970-01-01
          • 2021-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-21
          • 1970-01-01
          相关资源
          最近更新 更多