问题描述
我正在尝试找出一种方法,从 CSV 文件中的答案中找到最接近的数字。 我真的是python的初学者。我尝试了很多想法来让这里的任何事情都能奏效,但我应该多学习。
顺便说一句,有我的代码和 .cvs 文件: life-expectancy.csv
来自 CSV 文件的示例行:
Entity,Code,Year,Life expectancy (years)
Afghanistan,AFG,1950,27.638
Afghanistan,1951,27.878
Afghanistan,1952,28.361
Afghanistan,1953,28.852
...
这是我的代码:
import csv
i = 0
j = 0
average = 0
sum_age = 0
max_age = -1
max_year = -1
max_country = ""
min_age = 1000
min_year = 1000
min_country = ""
lowest_age = 100
lowest_year = 1000
lowest_country = ""
highest_age = -1
highest_year = -1
highest_country = ""
interest = int(input("Enter the year of interest: "))
print()
with open("life-expectancy.csv") as life_expct:
for line in life_expct:
i = i + 1
clean_line = line.strip()
splitting = clean_line.split(",")
if i > 1:
country = splitting[0]
year = int(splitting[2])
age = float(splitting[3])
if max_age < age:
max_age = age
max_year = year
max_country = country
if min_age > age:
min_age = age
min_year = year
min_country = country
if interest == year:
sum_age += age
j = j + 1
if highest_age < age:
highest_age = age
highest_year = year
highest_country = country
if lowest_age > age:
lowest_age = age
lowest_year = year
lowest_country = country
average = sum_age / j
print(f"The overall max life expectancy is: {max_age} from {max_country} in {max_year}")
print(f"The overall min life expectancy is: {min_age} from {min_country} in {min_year}")
print()
print(f"For the year {interest}:")
print(f"The average life expectancy across all countries was {average:.2f}")
print(f"The max life expectancy was in {highest_country} with {highest_age}")
print(f"The min life expectancy was in {lowest_country} with {lowest_age}")
print()
我试着把这样的代码放在最后,但我不知道该怎么做。 这是我尝试过的代码:
即。
given_value = 2
a_list = [1,5,8]
absolute_difference_function = lambda list_value : abs(list_value - given_value)
closest_value = min(a_list,key=absolute_difference_function)
代码的工作原理:
Enter the year of interest: 1965
The overall max life expectancy is: 86.751 from Monaco in 2019
The overall min life expectancy is: 17.76 from Iceland in 1882
For the year 1965:
The average life expectancy across all countries was 57.55
The max life expectancy was in Sweden with 73.81
The min life expectancy was in Mali with 29.489
所以,基本上我只想了解如何为最近的国家获得最接近的max/min并查看代码以进行学习和练习。
解决方法
也许您想查看 pandas 库,它是为像您这样的项目而设计的。这只是一个非常粗略的例子,很容易改进。
import pandas as pd
df = pd.read_csv("life-expectancy.csv",sep=",")
interest = int(input("Please enter year of interest:"))
df_interest = df[df['Year'] == interest]
interest_min = df_interest[df_interest['Life expectancy (years)'] == df_interest['Life expectancy (years)'].min()]
interest_ent,interest_code,interest_year,interest_exp = interest_min.squeeze().to_list()
print(f"The overall min life expectancy is: {interest_exp} from {interest_ent} in {interest_year}")