Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何允许用户输入年数并从该列表中提取平均、最小和最大预期寿命_Python_List_For Loop - Fatal编程技术网

Python 如何允许用户输入年数并从该列表中提取平均、最小和最大预期寿命

Python 如何允许用户输入年数并从该列表中提取平均、最小和最大预期寿命,python,list,for-loop,Python,List,For Loop,因此,对于一项任务,我必须允许用户输入一年,python将遍历整个.csv文件(我将链接该文件,以防它允许人们提供更好的帮助),找到该年内所有国家的预期寿命,然后将它们全部加起来,并显示平均值、最小值、,我一直在我的电脑上尝试不同的东西,但对于我的一生来说,我不知道该怎么做,甚至连想都会伤到我的头。如果有人能提供帮助,我将不胜感激。以下是我目前掌握的代码: filename = 'Life_expectancy.csv' rows = [] with open(filename) as le_f

因此,对于一项任务,我必须允许用户输入一年,python将遍历整个.csv文件(我将链接该文件,以防它允许人们提供更好的帮助),找到该年内所有国家的预期寿命,然后将它们全部加起来,并显示平均值、最小值、,我一直在我的电脑上尝试不同的东西,但对于我的一生来说,我不知道该怎么做,甚至连想都会伤到我的头。如果有人能提供帮助,我将不胜感激。以下是我目前掌握的代码:

filename = 'Life_expectancy.csv'
rows = []
with open(filename) as le_file: 
    next(le_file) 
    for line in le_file: 
 
        line = line.strip().split(",") 
        rows.append(line)

ages = [row[3] for row in rows]
min_age_idx = ages.index(min(ages))
max_age_idx = ages.index(max(ages))


details = rows[min_age_idx]
detailsElectricBoogaloo = rows[max_age_idx]
print('Name: {}, Code: {}, Year: {}, Life Expectancy: {}'.format(details[0], details[1], details[2], details[3]))
print('Name: {}, Code: {}, Year: {}, Life Expectancy:{}'.format(detailsElectricBoogaloo[0], detailsElectricBoogaloo[1], detailsElectricBoogaloo[2], detailsElectricBoogaloo[3]))
我还发现我无法链接文件,所以我将复制并粘贴csv数据的一部分

Entity,Code,Year,Life expectancy (years)
Afghanistan,AFG,1950,27.638
Afghanistan,AFG,1951,27.878
Afghanistan,AFG,1952,28.361
Afghanistan,AFG,1953,28.852
Afghanistan,AFG,1954,29.35
Afghanistan,AFG,1955,29.854
Albania,ALB,1950,54.191
Albania,ALB,1951,54.399
Albania,ALB,1952,54.875
Albania,ALB,1953,55.468
Albania,ALB,1954,56.18
Albania,ALB,1955,57.007
Algeria,DZA,1950,42.087
Algeria,DZA,1951,42.282
Algeria,DZA,1952,42.677
Algeria,DZA,1953,43.081
Algeria,DZA,1954,43.494
Algeria,DZA,1955,43.916

世界上每一个数据公开的国家的名单都是这样的,时间在1950年到2019年之间,有些国家在1923年到2019年之间,还有一些国家在这个时间段左右。我甚至想不起如何开始这项工作。

您可以查看pandas DataFrame,您可以在csv中轻松读取该数据框,然后根据您需要的年份进行筛选。

我建议使用csv内置模块解析您的csv,例如

import csv

with open('Life_expectancy.csv', 'r') as file_handler:
    data = [row for row in csv.reader(file_handler)]
但就如何过滤而言,您可以通过多种方式进行过滤:

for循环

results = []

for row in data:

    if row[2] == 'input_year':  # row[2] = third row, zero indexed

        results.append(row)

print(results)
滤器

results = [row for row in filter(lambda x: x[2] == 'input_year', data)]
print(results)
列表理解

results = [row for row in data if row[2] == 'input_year']
print(results)
然后是平均过程:

total_life_expectancy = sum([row[3] for row in results])
average_life_expectancy = total_life_expectancy / len(total_life_expectancy)

您甚至可以将这些功能组合到一个步骤中,并将其与上述功能组合在一起,但我建议您分步骤进行操作,以便更轻松地跟踪流程。

您可以使用内置模块
统计信息
,这是一个功能。要查找最小值和最大值,可以使用
min()/max()
函数

例如:

import csv
from statistics import mean

data = []
with open('data.csv', 'r', newline='') as f_in:
    csv_reader = csv.reader(f_in, delimiter=',', quotechar='"')
    next(csv_reader)  # skip headers
    for row in csv_reader:
        data.append(row)

year = input('Please enter the year: ')

average = mean(float(d[3]) for d in data if d[2] == year)
min_ = min((d for d in data if d[2] == year), key=lambda k: float(k[3]))
max_ = max((d for d in data if d[2] == year), key=lambda k: float(k[3]))

print('Statistics for year:', year)
print('-' * 80)
print('Average {:.2f}'.format(average))
print('Min :', min_)
print('Max :', max_)
Please enter the year: 1951
Statistics for year: 1951
--------------------------------------------------------------------------------
Average 41.52
Min : ['Afghanistan', 'AFG', '1951', '27.878']
Max : ['Albania', 'ALB', '1951', '54.399']
打印(例如):


我已经重命名了CSV文件
data.CSV
,并且我已经硬编码了
年份
,但是您知道了:

def main():
    import csv
    import statistics

    with open("data.csv") as file:
        reader = csv.DictReader(file)
        year = "1955"
        year_ages = list(map(lambda d: float(d["Life expectancy (years)"]), filter(lambda d: d["Year"] == year, reader)))

    minimum = min(year_ages)
    maximum = max(year_ages)
    average = statistics.mean(year_ages)

    print(year.center(32, "-"))
    print(f"The minimum life expectancy was {minimum:.2f} years.")
    print(f"The maximum life expectancy was {maximum:.2f} years.")
    print(f"The average life expectancy was {average:.2f} years.")

if __name__ == "__main__":
    main()
输出:

--------------1955--------------
The minimum life expectancy was 29.85 years.
The maximum life expectancy was 57.01 years.
The average life expectancy was 43.59 years.
>>> 

欢迎来到SO。这不是一个讨论论坛或教程。请花点时间阅读和阅读该页面上的其他链接。花些时间练习这些例子。它将让您了解Python提供的帮助您解决问题的工具。-<代码>如果有人能提供帮助-。这不是答案。谢谢你的帮助,非常有用