比较字典中列表之间的整数

2024-03-29 01:38:12 发布

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

我是Python的新手,我正在尝试为一个游戏制作一个计算器。我想在列表(字典中的值)和最大值来自的键之间的特定索引处获取最大整数。你知道吗

我试着把字典翻了一遍。你知道吗

raw_player_score = {'Matt' : [3, 5, 5, 4, 6, 9],
                    'Kyle' : [6, 9, 11, 5, 4, 3],
                    'Emily' : [4, 4, 5, 2, 1, 5]}

def extra_points(dict):
    for k, v in dict.items():
        for number in v:
            apple_king = max(v[1])
            print(apple_king)

final_dict = extra_points(raw_player_score)

我希望结果是9,因为Kevin在索引1处的数字最高,但是我得到的消息是“'int'object is not iteratable”


Tags: in游戏apple列表forraw字典extra
3条回答

硬编码所需的索引不是一个好主意;我建议您将其移到参数中。其他更改如下:

def extra_points(dict_, index):
    return max(                                    # Return maximum
        (                                          # From iterator
            (name, score_list[index])              # For name-score[index] tuples
            for name, score_list in dict_.items()  # In dict_
        ),
        key=lambda x: x[1]                         # Check the max by score[index]
    )[0]                                           # Get the name (zero element)

raw_player_score = {
    'Matt': [3, 5, 5, 4, 6, 9],
    'Kyle': [6, 9, 11, 5, 4, 3,],
    'Emily': [4, 4, 5, 2, 1, 5]
}

print(extra_points(raw_player_score, 1))

Kyle

其他答案中的所有建议都是正确的。我将提供一个更简单、老派的解决方案,它只做最少的工作,不需要创建任何额外的列表或进行任何排序。我认为作为一个新的Python程序员,最直接、最透明的方法可能是最好的:

raw_player_scores = {'Matt' : [3, 5, 5, 4, 6, 9],
                    'Kyle' : [6, 9, 11, 5, 4, 3,],
                    'Emily' : [4, 4, 5, 2, 1, 5]}

def extra_points(scores, pos):
    max_score = 0
    max_key = None
    for k, v in scores.items():
        if v[pos] > max_score:
            max_score = v[pos]
            max_key = k
    return max_key

max_key = extra_points(raw_player_scores, 1)
print(max_key)

结果:

Kyle

尽量不要使用dict作为变量名,您可以尝试:

raw_player_score = {'Matt': [3, 5, 5, 4, 6, 9], 'Kyle': [6, 9, 11, 5, 4, 3], 'Emily': [4, 4, 5, 2, 1, 5]}


def extra_points(d, ind):
    values_at_index = []
    for key in d:
        values_at_index.append((key, d[key][ind]))
    return max(values_at_index, key=lambda x: x[1])


print(extra_points(raw_player_score, 1))
print(extra_points(raw_player_score, 1)[0])

它给出:

('Kyle', 9)
Kyle

相关问题 更多 >