稍微改变输出 [英] Changing the output a bit

查看:56
本文介绍了稍微改变输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是:

voting_borda:

(str列表)->(str,int列表)的元组

(list of list of str) -> tuple of (str, list of int)

该参数是由4个元素组成的列表的列表,代表单次骑行的等级投票.

The parameter is a list of 4-element lists that represent rank ballots for a single riding.

Borda计数是通过根据排名分配分数来确定的.一方的第一选择排名获得3分,第二选择排名获得2分,第三选择排名获得1分. (如果获得第四名,则不会获得任何积分.)例如,上面显示的等级投票将为自由党议员贡献3分,为绿色议员贡献2分,为CPC贡献1分.得分最高的一方将赢得席位.

The Borda Count is determined by assigning points according to ranking. A party gets 3 points for each first-choice ranking, 2 points for each second-choice ranking and 1 point for each third-choice ranking. (No points are awarded for being ranked fourth.) For example, the rank ballot shown above would contribute 3 points to the Liberal count, 2 points to the Green count and 1 point to the CPC count. The party that receives the most points wins the seat.

返回一个元组,其中第一个元素是根据Borda Count的获胜方的名称,第二个元素是包含每个方的总点数的四元素列表.列表元素的顺序与PARTY_INDICES中各方的顺序相对应.

Return a tuple where the first element is the name of the winning party according to Borda Count and the second element is a four-element list that contains the total number of points for each party. The order of the list elements corresponds to the order of the parties in PARTY_INDICES.

这是我的代码:

def voting_borda(*args):
results = {}
for sublist in args:
    for i in range(0, 3):
        if sublist[i] in results:
            results[sublist[i]] += 3-i
        else:
            results[sublist[i]] = 3-i

winner = max(results, key=results.get)
results_sort = sorted(results,key=lambda x:x[1],reverse=True)
return winner, results_sort

但是,如果我尝试

voting_borda(['GREEN','NDP', 'LIBERAL', 'CPC'],['GREEN','CPC','LIBERAL','NDP'],['LIBERAL','NDP', 'CPC', 'GREEN'])

我明白了

('GREEN', {'NDP': 4, 'CPC': 3, 'GREEN': 6, 'LIBERAL': 5})

但是,我希望第一个参数成为获胜者(那部分很好),第二个参数只是值,并且也应按照PARTY_INDICES的顺序排列,即 PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX].

But, I want the first parameter to be the winner(that part is fine), and the second parameter to be just the values and also to be in the order of PARTY_INDICES which is PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX].

我可以做得更好的任何解决方案或方法吗?

any solutions or ways that i could make this better?

推荐答案

索引对象(NDP_INDEX等)确实是不必要的,而且不符合Python规范.只需使用字符串,如果您需要根据某些内容对其进行排序,请使用元组列表.

The index thing (NDP_INDEX etc.) is really unnecessary and un-pythonic. Just use the string, and if you need to sort it according to something, use lists of tuples.

 vv = [ ('republican',3), ('democrat',9), ('libertarian',73), ('green',-2) ]
 vsort = sorted(vv,key=lambda x:x[1],reverse=True)
 print(list(party for party, value in vsort))

您可以类似的方法来获得答案.讨厌为您完成整个任务...

You can do something similar to get your answer. Hate to do the entire assignment for you...

这篇关于稍微改变输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆