【问题标题】:Improving the code using more advanced Python libraries [closed]使用更高级的 Python 库改进代码 [关闭]
【发布时间】:2016-05-29 07:14:56
【问题描述】:

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

# 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

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    内置的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'
    

    【讨论】:

      【解决方案2】:

      你可以使用lambda操作符

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-22
        • 2014-01-31
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2015-06-08
        • 1970-01-01
        相关资源
        最近更新 更多