代码意外的Python结果

时间:2014-12-24 01:50:07

标签: python

dictionary = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections'], 'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

def most_class(dictionary):
    current_count = 0
    max_count = 0
    best_teacher = "none"
    for key in dictionary:
        for values in dictionary.values():
            current_count += 1
            if current_count > max_count:
                max_count = current_count
                best_teacher = key
    return best_teacher

目标是确定字典中哪个键具有最多值。答案应该是Daniel,但每次运行代码时我都会得到不同的答案(大概是由于字典的蟒蛇散列造成的。

任何人都可以解释为什么我会得到这个结果,以及如何修复它?

5 个答案:

答案 0 :(得分:1)

你在词典上迭代的次数超过你需要的次数,并且使得这比你需要的要困难得多。您可以通过将Python内置max()comprehensions结合使用来实现更多目的。试试这个:

dictionary = {
    'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms',
                     'Technology Foundations'], 
    'Kenneth Love': ['Python Basics', 'Python Collections'], 
    'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

# get maximum number of items any one person has
maximum_len = len(max(dictionary.values(), key=len))

# build a list of everyone with that number of items
most = [name for name, classes in dictionary.items() 
            if len(classes) == maximum_len]

print(most)

此代码打印:

  

[ '丹尼尔']

这不仅可以用理解来代替循环,如果出现平局,你会获得一个名单列表,而不仅仅是找到的第一个名称。例如,如果我们将字典定义更改为:

dictionary = {
    'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 
                     'Technology Foundations', 'other_item'], 
    'Kenneth Love': ['Python Basics', 'Python Collections'], 
    'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

然后将打印出来:

  

['Daniel','Jason Seifer']

答案 1 :(得分:1)

你有两个问题。

  1. 您需要每次都重置current_count,而不仅仅是在开始时。
  2. dictionary.values()为您提供了图书清单列表,而不是该作者的图书清单。
  3. 要解决第二个问题,我会使用for author, books in dictionary.items():而不是for key in dictionary:。然后,您不必每次都使用dictionary[key]。完成这些更改后,我们有:

    def most_class(dictionary):
        max_count = 0
        best_teacher = "none"
        for author, books in dictionary.items():
            current_count = 0
            for book in books:
                current_count += 1
                if current_count > max_count:
                    max_count = current_count
                    best_teacher = author
        return best_teacher
    

    此外,我可能会将if拉出循环:

    def most_class(dictionary):
        max_count = 0
        best_teacher = "none"
        for author, books in dictionary.items():
            current_count = 0
            for book in books:
                current_count += 1
            if current_count > max_count:
                max_count = current_count
                best_teacher = author
        return best_teacher
    

    此时,很明显我们根本不需要for循环,只能使用len

    def most_class(dictionary):
        max_count = 0
        best_teacher = "none"
        for author, books in dictionary.items():
            if len(books) > max_count:
                max_count = len(books)
                best_teacher = author
        return best_teacher
    

    您的代码也可能像其他人建议的那样使用max函数受益,尽管我可能会以不同的方式使用它:

    def most_class(dictionary):
        return max(dictionary.items(), default=('none', 0),
                   key=lambda item: len(item[1]))[0]
    

答案 2 :(得分:1)

你必须知道如何使用字典,然后我建议你这样做:

dictionary = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections'], 'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}

def most_class(dictionary):
    best_teacher = None
    class_of_best_teacher = 0
    for teacher_name in dictionary.keys():
        class_of_teacher = len(dictionary[teacher_name])
        if class_of_teacher > class_of_best_teacher :
            best_teacher = teacher_name
            class_of_best_teacher = class_of_teacher
    return best_teacher
print most_class(dictionary)

答案 3 :(得分:0)

您遍历字典中的键,但是您必须在每个键之间将 current_count 重置为零。因此, current_count max_count 一起计数最多为9,而 best_teacher 将是for循环遍历的最后一个键。

修复你的代码。

...
for key in dictionary:
    current_count = 0
    ...

它有效,但我想这样做:

best_teacher = sorted(dictionary.keys(), key=lambda x: len(dictionary[x]))[-1]

答案 4 :(得分:0)

  1. 为每个密钥重置current_count
  2. 应使用dictionary[key]代替dictionary.values()
  3. 以下代码返回Daniel。

    dictionary = {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'], 'Kenneth Love': ['Python Basics', 'Python Collections'], 'Daniel': ['Python Basics', 'Python Collections', 'test', 'test']}
    
    def most_class(dictionary):
        current_count = 0
        max_count = 0
        best_teacher = "none"
        for key in dictionary:
            current_count = 0
            for values in dictionary[key]:
                current_count += 1
                if current_count > max_count:
                    max_count = current_count
                    best_teacher = key
        return best_teacher