Python冠军计数器计划

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python冠军计数器计划相关的知识,希望对你有一定的参考价值。

我在使用world_cup_champions.txt文件时遇到了一些问题。当程序启动时,它应该读取文本文件并使用字典来存储所需的数据,使用赢得世界杯的每个国家的名称作为关键。我无法向用户显示“年”。以下是文本文件的示例:

Year,Country,Coach,Captain
1930,Uruguay,Alberto Suppici,José Nasazzi
1934,Italy,Vittorio Pozzo,Gianpiero Combi
1938,Italy,Vittorio Pozzo,Giuseppe Meazza
1950,Uruguay,Juan López,Obdulio Varela
1954,Germany,Sepp Herberger,Fritz Walter
1958,Brazil,Vicente Feola,Hilderaldo Bellini
1962,Brazil,Aymoré Moreira,Mauro Ramos
1966,England,Alf Ramsey,Bobby Moore

和代码:

def winners():
    f2 = open("world_cup_champions.txt","r+")

    dict_values ={}
    temp_list = []
    tmp_list1 = []
    tmp_list2 = []

    for l in f2:
        temp_list.append(l.strip())



    for val in temp_list:
        tmp_val = val.split(',')
        if tmp_val[1] not in dict_values:
            dict_values[tmp_val[1]] = 1
        else:
            dict_values[tmp_val[1]] += 1


    for key,value in dict_values.items():
        tmp_list2.append([key, value])
        tmp_list2.sort(key=lambda x: x[0])



    for val in tmp_list2:

        print(" " + val[0].ljust(14)  + " " + str(val[1]))




def main():


    print("FIFA World Cup Winners")
    print()
    print(" Country".ljust(14) + " Wins".center(9)  + "Years".rjust(14))
    print("{:15} {:5}".format("="*8, "="*5))

    winners()


if __name__ == "__main__":
    main()
答案

这是一个CSV文件,为什么不使用CSV阅读器?

import csv

def read_data(filename):
    wins = {}
    with open(filename) as filehandle:
        reader = csv.reader(filehandle)
        next(reader)  # skip header
        for row in reader:
            year, country, coach, captain = row
            if country not in wins:
                wins[country] = []
            wins[country].append([year, coach, captain])
    return wins

这给你一个很好的字典,国家名称和键和[year, coach, captain]列表作为值。

然后你可以这样做:

def print_winners(data):
    for country, wins in data.items():
        num_wins = len(wins)
        years = [win[0] for win in wins]
        print(country, num_wins, ', '.join(years))
另一答案

这是我解析它的方式。试图使这个功能尽可能具有教育意义。如果你想深入探索它,我建议你看看Panda's documentation并学习如何真正解析大而密集的CSV文件

 def parse(path_to_file):
    from_file = open(path_to_file, "r").read()
    ret = []
    keys, splitted = from_file.split("
")[0].split(","), from_file.split("
")[1:]
    for data in splitted:
        if not data: continue
        s = data.split(",")
        print(s, keys)
        q = zip(keys, s)
        ret.append(dict(q))
    return ret

parsed_dicts = parse("path_to_your_txt")
另一答案

如果你想忽略非常有用的csv模块,这里的代码中包含一些名为better,and working,但格式不是很好的输出的变量。

def winners():
    f2 = open("world_cup_champions.txt","r+")

    total_wins = {}
    years = {}
    lines = []
    country_list = []

    for line in f2:
        lines.append(line.strip())

    # Skip the first line with [1:]
    for line in lines[1:]:
        values = line.split(',')
        country = values[1]
        year = values[0]
        if country not in total_wins:
            total_wins[country] = 1
            years[country] = [year]
            country_list.append(country)
        else:
            total_wins[country] += 1
            years[country].append(year)


    for country in country_list:
        wins = total_wins[country]
        year_list = years[country]
        print(" " + country.ljust(14)),
        print(" " + str(wins)),
        print(year_list)

def main():


    print("FIFA World Cup Winners")
    print()
    print(" Country".ljust(14) + " Wins".center(9)  + "Years".rjust(14))
    print("{:15} {:5}".format("="*8, "="*5))

    winners()


if __name__ == "__main__":
    main()

你这样做的方式,你把错误的信息放到你唯一的字典中。您需要一个不同的数据类型来保存字符串,整数和整数列表。您可以将字典的值设置为一个列表,该列表既包含胜利总数,也包含年份列表。

另一答案

一些值得思考的东西:

import pandas as pd

def main():

    df = pd.read_csv('data.txt')
    print(df)


if __name__ == "__main__":
    main()

产量

   Year  Country            Coach             Captain
0  1930  Uruguay  Alberto Suppici        José Nasazzi
1  1934    Italy   Vittorio Pozzo     Gianpiero Combi
2  1938    Italy   Vittorio Pozzo     Giuseppe Meazza
3  1950  Uruguay       Juan López      Obdulio Varela
4  1954  Germany   Sepp Herberger        Fritz Walter
5  1958   Brazil    Vicente Feola  Hilderaldo Bellini
6  1962   Brazil   Aymoré Moreira         Mauro Ramos
7  1966  England       Alf Ramsey         Bobby Moore
另一答案

您可以使用字典和列表表达式执行以下操作(以相同的方式可以打印教练和队长):

def winners():
    # read file 
    with open("file.txt","r") as f:
        lines = f.readlines()

    # init dict
    dict_values = {}

    # process
    for line in lines[1:]:
        year    = line.split(",")[0]
        country = line.split(",")[1]        
        coach   = line.split(",")[2]
        captain = line.split(",")[3]     

        # fill in dict
        if not(country in dict_values.keys()):
            dict_values[country] = [[year, coach, captain]]

        else: 
            dict_values[country].append([year, coach, captain])

    # sort dict
    sorted_list = sorted(dict_values.items(),
                         key = lambda x: len(x[1]),
                         reverse = True)

    # printing
    for country, values in sorted_list:
        years    = [value[0] for value in values]
        coaches  = [value[1] for value in values]
        captains = [value[2] for value in values]
        print(" " + country.ljust(16) 
              + " " + str(len(years)).ljust(10) + " "  
              + str(years).replace('[', "").replace(']', "").replace("'", ""))


def main():
    # printing
    print("FIFA World Cup Winners")
    print()
    print(" Country".ljust(14) + " Wins".center(9)  + "Years".rjust(14))
    print("{:15} {:11} {:}".format("="*9, "="*6, "="*12))

    winners()


if __name__ == "__main__":
    main()

输出:

 Country         Wins           Years
=========       ======      ============
 Uruguay          2          1930, 1950
 Italy            2          1934, 1938
 Brazil           2          1958, 1962
 Germany          1          1954
 England          1          1966

以上是关于Python冠军计数器计划的主要内容,如果未能解决你的问题,请参考以下文章

[新星计划] Python内存管理 | 引用计数垃圾回收内存池机制

[新星计划] Python内存管理 | 引用计数垃圾回收内存池机制

HackathonBSV编程马拉松冠军计划打造一个动态的比特币网络

python 使用数据库按计划对电子邮件进行计数

十大视频场景化应用工具+五大视频领域冠军/顶会算法开源

[新星计划] Python手撕代码 | 十大经典排序算法