如何更改输出? (Python,列表,词典帮助)

时间:2012-12-02 03:48:23

标签: python python-3.2

  

可能重复:
  changing the output

这是代码:

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,绿色和cpc)我只需要值,如何编辑代码来实现?

编辑:

我在测试上述代码后得到的错误消息(使用:>>> voting_borda([['NDP','CPC','GREEN','LIBERAL'],['NDP','CPC ','LIBERAL','GREEN'],['NDP','CPC','GREEN','LIBERAL']])

追踪(最近一次通话):   文件“”,第1行,in     voting_borda([['NDP','CPC','GREEN','LIBERAL'],['NDP','CPC','LIBERAL','GREEN'],['NDP','CPC','GREEN ', '自由派']])   在voting_borda中输入文件“C:\ Users \ mycomp \ Desktop \ work \ voting_systems.py”,第144行     winner = max(results,key = results.get) NameError:未定义全局名称“结果”

  
    
      

    
  

2 个答案:

答案 0 :(得分:1)

对于Python 2.7:

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

对于Python 3.x:

return winner, list(results.values())

答案 1 :(得分: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”(如this question中所述)