Python列表数据分析

时间:2015-01-11 14:14:21

标签: python list average

我需要在python中创建一个小程序,我必须在列表中分析数据。 列表包含以下列:国家,年份,男性移民,男性移民,女性移民,女性移民

我要做的是首先询问用户他们想要获取信息的国家/地区。计划需要多年来获得平均移民,并在移民超过平均值时打印出来。最后,我必须打印出一张表,其中有移民超过移民的国家名称和年份。

我还是初学者,我一直在写这篇文章。我希望它不那么困难。

1 个答案:

答案 0 :(得分:0)

data = [
    # some made-up numbers for illustration
    ("France", 2006, 64026, 72527, 87442, 98435),
    ("France", 2007, 82051, 75285, 97193, 69527),
    ("France", 2008, 88827, 51960, 77807, 81725),
    ("Germany", 2006, 85653, 83989, 66603, 66559),
    ("Germany", 2007, 85431, 83590, 88482, 87827),
    ("Germany", 2008, 67184, 96350, 84947, 67874),
    ("Greece", 2006, 72062, 55844, 51758, 53004),
    ("Greece", 2007, 58566, 62006, 65323, 80320),
    ("Greece", 2008, 71298, 69158, 74774, 93267)
]

def average(lst):
    return sum(lst) / (len(lst) or 1)

def main():
    # prompt for country
    country = input("For which country? ")

    # filter data by specified country
    country_data = [row for row in data if row[0]==country]

    # get average yearly emigration
    avg_emigration = average([row[3] + row[5] for row in country_data])

    # print years in which emigration exceeds average
    print("Above-average emigration in:")
    for row in country_data:
        if row[3] + row[5] >= avg_emigration:
            print(row)

    # I'll leave the last bit for you to figure out;
    # very similar to the preceding clause

if __name__ == "__main__":
    main()

一样运行
>>> main()
For which country? France
Above-average emigration in:
('France', 2006, 64026, 72527, 87442, 98435)