编写一个名为“ total_population”的函数,该函数将一个字符串然后一个列表作为参数,其中该字符串表示一个CSV文件的名称,该文件包含格式为“ CountryCode,CityName,Region,Popple,Latitude,Longitude”的城市数据,第二个参数是一个列表,其中每个元素本身就是一个包含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
答案 0 :(得分:0)
您只需要将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