【问题标题】:How to print only the highest value for a key?如何仅打印键的最高值?
【发布时间】:2015-02-03 18:33:59
【问题描述】:

我在尝试解决这个任务时遇到了一个问题,所以在失败了几次之后我就在这里,我想知道当一个键存储多个时,我怎么才能只打印一个键(名称)的最高值(分数)值,例如:

Rob Scored: 3,5,6,2,8
Martin Scored: 4,3,1,5,6,2
Tom Scored: 7,2,8

名称是键,分数是值。现在我希望得到 ​​p> 的输出

 Martin Scored: 6
 Rob Scored: 8
 Tom Scored: 8

但是,当我尝试使用 max 函数时,它会忽略字母顺序。就像这不是一个要求以及其他分数必须保留以供以后阶段使用的事实一样。

from collections import OrderedDict
dictionary = {}

for line in f:
    firstpart, secondpart = line.strip().split(':')
    dictionary[firstpart.strip()] = secondpart.strip()
    columns = line.split(": ")
    letters = columns[0]
    numbers = columns[1].strip()
    if d.get(letters):
        d[letters].append(numbers)
    else:
        d[letters] = list(numbers)
sorted_dict = OrderedDict(
sorted((key, list(sorted(vals, reverse=True))) 
       for key, vals in d.items()))
print (sorted_dict)

【问题讨论】:

  • 这个问题今天已经有人问过了。奇怪:D
  • 你的输入文件是什么样的?
  • 它是一个 txt 文件,它看起来像第一个突出显示的示例,Rob Scored: .... rob 是键,分数是值

标签: python sorting dictionary


【解决方案1】:

这就是你想要的:

# You don't need to use an OrderedDict if you only want to display in
# sorted order once
score_dict = {} # try using a more descriptive variable name

with open('score_file.txt') as infile:
    for line in infile:
        name_field, scores = line.split(':') # split the line
        name = name_field.split()[0]         # split the name field and keep 
                                             #     just the name

        # grab all the scores, strip off whitespace, convert to int
        scores = [int(score.strip()) for score in scores.split(',')]

        # store name and scores in dictionary
        score_dict[name] = scores

        # if names can appear multiple times in the input file, 
        # use this instead of your current if statement:
        #
        # score_dict.setdefault(name, []).extend(scores)

# now we sort the dictionary keys alphabetically and print the corresponding
# values
for name in sorted(score_dict.keys()):
    print("{} Scored: {}".format(name, max(score_dict[name])))

请阅读此文档:Code Like a Pythonista。它对如何编写更好的代码有很多建议,并且我在这里学习了dict.setdefault() 方法来处理值是列表的字典。

另一方面,在您的问题中,您提到了使用 max 函数的尝试,但该函数不在您提供的代码中的任何位置。如果您在问题中提到失败的尝试完成某些事情,您也应该包含失败的代码,以便我们可以帮助您调试它。我能够为您提供一些完成任务的代码以及其他一些建议,但如果您不提供原始代码,我将无法调试它。由于这显然是一个家庭作业问题,因此您绝对应该花一些时间弄清楚为什么它一开始就不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2021-04-02
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多