2016-04-02 88 views
1

好的内比较子列表,所以我想写计数称为成对比较排名选票的方法。我应该指定,我是一个完整的新手,当涉及到的每一个词的意义上编写代码。到目前为止,我已经成功地创造了选票(感谢这个网站的其他用户),并根据他们的位置分成排名对。接下来,我需要把它们分成不同的列表,以便在每个有序对考生在一起秩无关(这是一个如何确定候选人如何相较于其他人做的一部分)。这里是我到目前为止的代码:成对比较:一个列表

import itertools 
import random 
import collections 
candidates = ['Trump', 'Cruz', 'Rubio', 'Carson', 'Fiorina'] 
def simul_ballots(num_voters): 
    ballots = [] 
    choice = candidates[:] 
    for _ in range(num_voters): 
     random.shuffle(choice) 
     ballots.append(choice[:]) 
    return ballots 
n=3 
ballots = simul_ballots(n) 
i=0 
m=0 
oPairs = [] 
while i < n: 
    for a, b in itertools.combinations(ballots[i], 2): 
     x = (a,b) 
     x 
     ops = list(x) 
     oPairs.append(ops) 
    i += 1 
oPairs 

l = len(oPairs)-1 
k=0 
j=(k+1) 
while (k < l): 
    print oPairs[k] 
    while (j < l): 
     #if all (x in oPairs[i] for x in oPairs[j]): 
     if (set(oPairs[k])==set(oPairs[j])): 
      print oPairs[j] 
      j+=1 
    k+=1 

到目前为止,我被困在这最后一节。我似乎无法理解如何给每个子列表进行比较,以其他(不重复,其重要的是有子列表相同数量的,我开始在这个例子中,我只产生3套票为目的出于测试目的,所以应该有三个有序对使用相同的考生,无论定位的(我需要定位后,以高分考生)。在正确的方向上没有任何提示或建议,将不胜感激!

回答

0

我我不知道你在用你的代码做什么

既然你已经导入了collections,好像你可能知道Counter是一个很好的工具来计算两两比较的结果, d迭代罐对使用didates:

for can1, can2 in combinations(candidates, 2): 

然后,遍历每次投票:

for ballot in ballots: 

如果can1首先出现在选票,他们拿到一分,否则can2得一分。这可以通过检查:

if ballot.index(can1) < ballot.index(can2): 

选票统计出来(对于仅此一对)后,如果can1赢得了更多的选票,他们拿到一分,否则,如果can2赢得了更多的选票,他们拿到一分东西,他们都得到了半分。

把所有这些组合起来可能看起来像:

from collections import Counter 

vote_counter = Counter() 

for can1, can2 in combinations(candidates, 2): 
    count1, count2 = 0, 0 

    for ballot in ballots: 
     if ballot.index(can1) < ballot.index(can2): 
      count1 += 1 
     else: 
      count2 += 1 

    if count1 > count2: 
     vote_counter[can1] += 1 
    elif count1 < count2: 
     vote_counter[can2] += 1 
    else: 
     vote_counter[can1] += 0.5 
     vote_counter[can2] += 0.5