【问题标题】:Total population of countries国家总人口
【发布时间】:2019-03-23 19:35:20
【问题描述】:

编写一个名为“total_population”的函数,该函数接受一个字符串和一个列表作为参数,其中该字符串表示包含格式为“CountryCode、CityName、Region、Population、Latitude、Longitude”的城市数据的 CSV 文件的名称,以及第二个参数是一个列表,其中每个元素本身就是一个列表,其中包含 3 个字符串作为按此顺序表示 CountryCode、CityName 和 Region 的元素。返回列表中所有城市的总人口。请注意,城市必须与国家、名称和地区相匹配,以确保读取的城市正确。

我几乎把所有东西都设置得很好(我认为),但我在尝试最后总结人口时遇到了问题。我尝试了 3 种每次添加 +1 并在最后添加所有内容的方法,但我似乎无法做到正确。

import csv
def total_population(filename, cityinfo): # have CSV file and list that is a line with the function
    totalPop = 0
    #count = 0
    for str3 in cityinfo: # rep. the three catagorize 
        countryCode = str3[0]
        cityName = str3[1]
        region = (str3[2])  

    with open (filename, newline='') as f:    # the list contains 3 strings(Country code, city name, region)
        readCsv = csv.reader(f)
        for line in readCsv:
            if (line[0] == countryCode):
                if (line[1] == cityName):
                    if ((line[2]) == region):  
                        #count += 1
                        totalPop = totalPop + int(line[3])
                        #totalPop += int(line[3])
    return totalPop

提交代码时不断收到的错误消息。

返回:19561 预计:25187

【问题讨论】:

  • 您能以某种方式分享cityinfo 的值以及您用于测试的csv 文件吗?
  • csv 文件是无限的并且与 cityinfo 相关联。例如 am,horom,07,1893,40.6541667,43.8822222。来自 csv 的 3 个点和来自 cityinfo 的 3 个点,它是一个列表。该死,我无法很好地解释这一点..对不起
  • 另外,我建议您更改问题的标题和描述,以专注于您遇到的问题(不需要解释整个练习)。
  • 我知道你的意思,但这是我作业中的确切问题,我的问题写在第二段。谢谢你的建议。
  • 也许您的 if 声明之一没有注册,所以您忽略了部分人口?

标签: python csv


【解决方案1】:

您只需要将 with/as 语句放在 for 循环中,以便它对 cityinfo 中的每个元素执行此操作,因为它不仅仅是一个数组。它是多个,所以你只得到第一个

import csv
def total_population(filename, cityinfo):
    totalPop = 0
    #count = 0
    for str3 in cityinfo:
        countryCode = str3[0]
        cityName = str3[1]
        region = (str3[2])  
        with open (filename, newline='') as f:
            readCsv = csv.reader(f)
            for line in readCsv:
                if (line[0] == countryCode):
                    if (line[1] == cityName):
                        if ((line[2]) == region):  
                            totalPop = totalPop + int(line[3])
        return totalPop

【讨论】:

  • 谢谢你的帮助,但它似乎不起作用,你发现代码只选择了列表的第一个元素。我怎样才能让代码拾取所有元素并拥有它的总数。在这种情况下,它将导致总人口数。
猜你喜欢
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 2011-11-01
  • 2019-04-22
  • 1970-01-01
  • 2014-09-08
相关资源
最近更新 更多