You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现仅将字典指定key的数值列表乘以给定整数

问题修正方案

你的代码问题在于遍历了字典中所有键对应的值,没有判断是否是传入的指定名称,因此所有用户的分数列表都被修改。同时你提供的测试代码存在语法错误,字典的键值对分隔符错误使用了=,需要替换为:。

修改后的函数代码

def multiply_scores(scores, name, number):
    # 先判断指定名称是否存在于字典中,避免抛出KeyError
    if name not in scores:
        return
    # 仅取出指定名称对应的分数列表进行修改
    target_list = scores[name]
    for index in range(len(target_list)):
        target_list[index] = round(target_list[index] * number)

列表是Python中的可变对象,直接修改原列表对象就会同步到字典中,不需要额外返回值。

修正后的测试代码

def main():
    scores ={'Bella': [2, 8, 3], 'Jack': [8, 9, 7, 4]}
    multiply_scores(scores, 'Bella', 3)
    print(scores['Bella'])
    print(scores['Jack'])

运行输出

[6, 24, 9]
[8, 9, 7, 4]

符合预期要求。

内容的提问来源于stack exchange,提问作者user15103706

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:39:02