Я пытаюсь найти способ найти ближайший номер из моих ответов в файле CSV. Я действительно новичок в питоне. Я перепробовал так много идей, как заставить что-то здесь работать, но мне нужно больше учиться.
Кстати, вот мой код и файл .cvs: life- ожидание.csv
Примеры строк из файла 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
...
Вот мой код:
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()
Я пытался поставить такой код в конце, но я не знаю, как это сделать. Вот код, который я пробовал:
ie.
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 для ближайшей страны, и посмотреть код для изучения и практики.