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

2024-03-28 18:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
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)党的名称,我只需要值,我如何编辑代码来实现这一点?你知道吗

编辑:

我在测试上述代码后收到的错误消息(with:>;>;voting\u borda([['NDP','CPC','GREEN','LIBERAL'],['NDP','CPC','LIBERAL','GREEN','LIBERAL'],['NDP','CPC','GREEN','LIBERAL']])

回溯(最近一次呼叫): 文件“”,第1行,在 投票_borda([['NDP','CPC','GREEN','LIBERAL'],['NDP','CPC','LIBERAL','GREEN'],['NDP','CPC','CPC','GREEN','LIBERAL']]) 文件“C:\Users\mycomp\Desktop\work\voting_系统.py“,第144行,在borda” 获胜者=最大值(结果,关键点)=结果。获取) NameError:未定义全局名称“results”

^{2}$

Tags: 代码in名称编辑forargsgreenresults
2条回答

对于Python 2.7:

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

对于Python 3.x:

return winner, list(results.values())

非常老式的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中所述)

相关问题 更多 >