Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用更高级的Python库改进代码_Python_Dictionary - Fatal编程技术网

使用更高级的Python库改进代码

使用更高级的Python库改进代码,python,dictionary,Python,Dictionary,我应该使用哪些高级Python库来使下面的代码更加简洁和整洁? 内置函数可与一个键函数一起使用,该键函数将应用于iterable中的每个元素,以确定最大元素。只需返回maxdict项与其值长度相关的键: def most_classes(d): return max(d.items(), key=lambda i: len(i[1]))[0] # items(): list of (key, value) pairs of dictionary # [1]: value

我应该使用哪些高级Python库来使下面的代码更加简洁和整洁?

内置函数可与一个键函数一起使用,该键函数将应用于iterable中的每个元素,以确定最大元素。只需返回max
dict
项与其值长度相关的键:

def most_classes(d):
    return max(d.items(), key=lambda i: len(i[1]))[0]
    # items(): list of (key, value) pairs of dictionary
    # [1]: value of item
    # [0]: key of item

# or even shorter, as Saish suggests:
def most_classes(d):
    return max(d, key=lambda k: len(d[k]))


> d = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
       'Kenneth Love': ['Python Basics', 'Python Collections']}
> most_classes(d)
'Jason Seifer'

您可以使用
lambda
运算符

max(dict, key=lambda x:len(dict[x]))
max(dict, key=lambda x:len(dict[x]))