如何找到可以包含-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!!在
您可以count occurences为0,并测试它们是否为多数。在
如果使用的是python>;=3.4,则可以使用statistics.mode,在没有唯一模式时捕捉
StatisticsError
:statistics实现本身使用一个Counter dict:
^{pr2}$另一种使用计数器并捕获空列表的方法:
我假设0票算作票。所以
sum
不是一个合理的选择。在试试计数器:
所以您可以编写如下代码:
^{pr2}$相关问题 更多 >
编程相关推荐