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

时间:2016-05-29 07:14:57

标签: python dictionary

我应该使用哪些高级Python库来使以下代码更简洁,更整洁? http://wiki.pentaho.com/display/EAI/HTTP+Client

# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
#  'Kenneth Love': ['Python Basics', 'Python Collections']}
#
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewhere
# too!
#
# Your code goes below here.
def most_classes(dict):
    for item in dict:
        count = 0
        max = 0
        teacher = None
        for course in dict[item]:
            count += 1
        if count > max:
            max = count
            teacher = item
    return teacher

2 个答案:

答案 0 :(得分:1)

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

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'

答案 1 :(得分:1)

您可以使用php bin/console cache:clear --env=prod --no-debug 运算符

lambda