【发布时间】: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声明之一没有注册,所以您忽略了部分人口?