使我的代码更具可读性

时间:2016-03-15 21:37:09

标签: python list

所以我想让我的输出代码更具可读性,我需要一些帮助,因为我不知道该怎么做,因为现在它输出了这个:

OrderedDict([('David', 63), ('Adamz', 10), ('Daloe', 1), ('Avid', 1), ('Aaaab', 1), ('Dlo', 1), ('D', 0), ('Da', 0), ('N', 0), ('Adz', 0)])

我想删除OrderedDict并将其打印出来,如下所示:

David: 63
Adamz: 10
Daloe: 1
Avid: 1

这是代码:

def alphabetically(some_data):
    return OrderedDict(
        (k, some_data[k]['scores'])
        for k in sorted(some_data)
    )


def by_score(some_data, descending=True):
    return OrderedDict(
        (k, sum(some_data[k]['scores']))
        for k in sorted(some_data,
                        key=lambda k: sum(some_data[k]['scores']),
                        reverse=descending)
    )


def by_average(some_data, descending=True):
    def average(scores):
        return float(sum(scores)) / len(scores)
    return OrderedDict(
        (k, average(some_data[k]['scores']))
        for k in sorted(some_data,
                        key=lambda k: average(some_data[k]['scores']),
                        reverse=descending)

这是输出代码的方式和位置:

data = defaultdict(dict)
with open(filename, 'r+') as f:
    for line in f.read().splitlines():
        name, score = line.split(' : ')
        scores = data[name].get('scores', [])
        scores.append(int(score))
        data[name]['scores'] = scores

if get_bool_input("Do you wish to view the previous results from your class: "):
    while True:                                                                  
        selection= input('Do you wish to view the results in: Alphabetical order (A),''\n                                   scores highest to lowest (B),''\n                                   or average score highest to lowest?(C): '
                         )
        if selection not in ['A', 'B', 'C']:
            print ("Error, type in A, B or C.")
            continue
        if selection == 'A':
            print (alphabetically(data))                                         
        elif selection == 'B':
            print (by_score(data))                                               
        elif selection == 'C':
            print (by_average(data))                                             
        break                                                                    

else:
    input ("Press any key to exit")

2 个答案:

答案 0 :(得分:1)

您需要进行一些格式化打印:

for key in my_ordered_dict:
    print "%s: %s" % (key, my_ordered_dict[key], )

如果您要多次这样做,那么值得创建一个可以调用的好功能。

def pretty_print_dict(my_dict):
    for key in my_dict:
        print "%s: %s" % (key, my_dict[key], )

或者对于Python 3,您可以尝试这样的事情:

def pretty_print_dict(my_dict):
    for key in my_dict:
        print('{0}: {1}'.format(key, my_dict[key]))

然后你打电话给他们中的任何一个:

if selection == 'A':
    pretty_print_dict(alphabetically(data))

答案 1 :(得分:0)

您还没有展示出如何输出函数结果,甚至调用函数,但为什么不创建一个新函数来循环包含该函数并按照您喜欢的方式打印元素?