-2

可能重复:
更改输出

这是代码:

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)
    return winner, results

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

产生的输出是

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

我不希望输出中的政党名称(自由党、ndp、green 和 cpc)我只需要这些值,如何编辑代码来实现这一点?

编辑:

测试上述代码后我收到的错误消息(带有: >>>voting_borda([['NDP', 'CPC', 'GREEN', 'LIBERAL'],['NDP', 'CPC', 'LIBERAL', '绿色'],['NDP','CPC','绿色','自由']])

回溯(最近一次通话):文件“”,第 1 行,在 vote_borda([['NDP', 'CPC', 'GREEN', 'LIBERAL'],['NDP', 'CPC', 'LIBERAL', 'GREEN'],['NDP', 'CPC', 'GREEN', 'LIBERAL']]) 文件“C:\Users\mycomp\Desktop\work\voting_systems.py”,第 144 行,在 vote_borda 中获胜者 = max (results, key=results.get) NameError: global name 'results' is not defined

4

2 回答 2

1

对于 Python 2.7:

return winner, [value for value in results.values()])

对于 Python 3.x:

return winner, list(results.values())
于 2012-12-02T03:58:27.993 回答
0

非常老式的 Python:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

myResults=(['GREEN','NDP', 'LIBERAL', 'CPC'],
    ['GREEN','CPC','LIBERAL','NDP'],
    ['LIBERAL','NDP', 'CPC', 'GREEN'])

def count(results):
  counter = dict()
  for resultList in results:
    for result in resultList:
      if not(result in counter):
        counter[result] = 1
      else:
        counter[result] += 1
  print "counter (before): %s" % counter
  return counter.values()


if __name__ == "__main__":
  print "%s" % count(myResults)

如果您使用 Python >= 2.7,请检查“ collections.Counter ”(如本问题所述)

于 2012-12-02T04:05:17.073 回答