在列表python中查找1、1和0的多数票

2024-09-30 22:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找到可以包含-1、1和0的列表的多数票?

例如,给定一个列表:

x = [-1, -1, -1, -1, 0]

大多数是-1,因此输出应该返回-1

另一个例子,给出一个列表:

^{pr2}$

多数票将是1

当我们平局时,多数票应返回0,例如:

x = [1, 1, 1, -1, -1, -1]

这也应该返回零:

x = [1, 1, 0, 0, -1, -1]

获得多数票的最简单的情况似乎是把名单加起来,然后检查它是否定的、正面的还是0。在

>>> x = [-1, -1, -1, -1, 0]
>>> sum(x) # So majority -> 0
-4
>>> x = [-1, 1, 1, 1, 0]
>>> sum(x) # So majority -> 1
2
>>> x = [-1, -1, 1, 1, 0]
>>> sum(x) # So majority is tied, i.e. -> 0
0

在总数之后,我可以做这个检查以获得多数票,即:

>>> x = [-1, 1, 1, 1, 0]
>>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0
>>> majority
1
>>> x = [-1, -1, 1, 1, 0]
>>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0
>>> majority
0

但如前所述,它很难看:Python putting an if-elif-else statement on one line而且不是Python。在

所以解决办法似乎是

>>> x = [-1, -1, 1, 1, 0]
>>> if sum(x) == 0:
...     majority = 0
... else:
...     majority = -1 if sum(x) < 0 else 1
... 
>>> majority
0

已编辑

但是有些情况下sum()不起作用,@RobertB的例子

>>> x = [-1, -1, 0, 0, 0, 0]
>>> sum(x) 
-2

但在这种情况下,多数票应该是0!!在


Tags: 列表ifsois情况else例子sum
3条回答

您可以count occurences为0,并测试它们是否为多数。在

>>> x = [1, 1, 0, 0, 0]
>>> if sum(x) == 0 or x.count(0) >= len(x) / 2.0:
...     majority = 0
... else:
...     majority = -1 if (sum(x) < 0) else 1
... majority
0

如果使用的是python>;=3.4,则可以使用statistics.mode,在没有唯一模式时捕捉StatisticsError

from statistics import mode, StatisticsError

def majority(l):
    try:
        return mode(l)
    except StatisticsError:
        return 0

statistics实现本身使用一个Counter dict:

^{pr2}$

另一种使用计数器并捕获空列表的方法:

def majority(l):
    cn = Counter(l).most_common(2)
    return 0 if len(cn) > 1 and cn[0][1] == cn[1][1] else next(iter(cn),[0])[0]

我假设0票算作票。所以sum不是一个合理的选择。在

试试计数器:

>>> from collections import Counter
>>> x = Counter([-1,-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0])
>>> x
Counter({0: 8, 1: 4, -1: 3})
>>> x.most_common(1)
[(0, 8)]
>>> x.most_common(1)[0][0]
0

所以您可以编写如下代码:

^{pr2}$

相关问题 更多 >