李素琴 发表于 2023-1-7 11:04:04

这个代码到底哪里出了问题啊


members = {
    "鱼C工作室" : {"小甲鱼":83, "不二如是":89, "二师兄":64, "小师妹":75, "鱼小二":96},
    "复仇者联盟" : {"钢铁侠":85, "绿巨人":39, "黑寡妇":82, "鹰眼":73, "雷神":99},
    "奥特曼家族" : {"迪迦":99, "艾斯":84, "泰罗":63, "佐菲":78, "赛文":78}}
x = []
for k,v in members.items():
    x.append(str(k+":"+min(v,key=v.get)))
print(x)


members = {
    "鱼C工作室" : {"小甲鱼":83, "不二如是":89, "二师兄":64, "小师妹":75, "鱼小二":96},
    "复仇者联盟" : {"钢铁侠":85, "绿巨人":39, "黑寡妇":82, "鹰眼":73, "雷神":99},
    "奥特曼家族" : {"迪迦":99, "艾斯":84, "泰罗":63, "佐菲":78, "赛文":78}}
x = [':'.join((i, min(members.items(), key = lambda x:x))) for i in members]
print(x)



members = {
    "鱼C工作室" : {"小甲鱼":83, "不二如是":89, "二师兄":64, "小师妹":75, "鱼小二":96},
    "复仇者联盟" : {"钢铁侠":85, "绿巨人":39, "黑寡妇":82, "鹰眼":73, "雷神":99},
    "奥特曼家族" : {"迪迦":99, "艾斯":84, "泰罗":63, "佐菲":78, "赛文":78}}
x = [':'.join(k,min(v,key=v.get) for k,v in members.items())]
print(x)

为什么一、二可以运行,三就报错呢

isdkz 发表于 2023-1-7 11:18:03

本帖最后由 isdkz 于 2023-1-7 11:21 编辑

一:在生成器表达式里面 k,min(v,key=v.get) 需要加一个括号表示元组

二:因为生成器表达式的生成元素都是元组,所以不能直接用 join

members = {
    "鱼C工作室" : {"小甲鱼":83, "不二如是":89, "二师兄":64, "小师妹":75, "鱼小二":96},
    "复仇者联盟" : {"钢铁侠":85, "绿巨人":39, "黑寡妇":82, "鹰眼":73, "雷神":99},
    "奥特曼家族" : {"迪迦":99, "艾斯":84, "泰罗":63, "佐菲":78, "赛文":78}}
x = [':'.join(i) for i in ((k,min(v,key=v.get)) for k,v in members.items())]
print(x)

李素琴 发表于 2023-1-7 12:01:00

谢谢答复!我想再问一下 key=v.get 是什么意思,什么用法

李素琴 发表于 2023-1-7 12:01:30

key是取最小值的依据,但是v.get是什么用法
页: [1]
查看完整版本: 这个代码到底哪里出了问题啊