python - 返回元组列表时字符串索引超出范围
问题描述
让我为标题道歉,模组可以随意将其编辑为您认为更合适的内容。我很难找到一个更合适的标题。
我正在做一个练习。我将分别实现两个类,Country 和 CountryDirectory。该练习涉及通过用于添加/删除国家的方法来操作此国家目录,以更新任意国家的人口和地区等。
我们得到了一个驱动程序来测试我们的方法。特别是有一种方法,“populationDensityFilter”,它给我带来了问题。这种方法用于确定哪些国家属于选定的区间。更具体地说,它将最小值和最大值作为人口密度范围的参数。它应该返回一个密度在该范围内的国家列表。它应该返回一个对列表,其中每对是一个国家名称和一个人口密度。该列表应按从最高密度到最低密度的降序排列。如果范围内没有任何内容,它应该返回一个空列表。
我的代码可以正确返回给定范围内的国家/地区,但是,当与给定的测试方法配对时,它会返回错误。我相信这是因为测试方法需要一个元组,其中包含索引 0 中的国家和索引 1 中的密度。感谢您的帮助,谢谢。
有两个文本文件被读取:
大陆.txt
China,Asia
United States of America,North America
Brazil,South America
Japan,Asia
Canada,North America
Indonesia,Asia
Nigeria,Africa
Mexico,North America
Egypt,Africa
France,Europe
Italy,Europe
South Africa,Africa
South Korea,Asia
Colombia,South America
数据.txt
Country|Population|Area
China|1,339,190,000|9,596,960.00
United States of America|309,975,000|9,629,091.00
Brazil|193,364,000|8,511,965.00
Japan|127,380,000|377,835.00
Canada|34,207,000|9,976,140.00
Indonesia|260,581,100|1,809,590.97
Nigeria|186,987,563|912,134.45
Mexico|128,632,004|1,969,230.76
Egypt|93,383,574|1,000,000.00
France|64,668,129|541,656.76
Italy|59,801,004|300,000.00
South Africa|54,978,907|1,222,222.22
South Korea|50,503,933|98,076.92
Colombia|48,654,392|1,090,909.09
这是我的代码:
# My code
def populationDensityFilter(self, min, max):
for element in self._catalogue:
if self._catalogue[element].getPopulationDensity() >= min and self._catalogue[element].getPopulationDensity() <= max:
print(element) # should be return
# Given test method that my code has to work in conjunction with.
def testDensityFilter(countryDirectory):
print()
low = input(" Enter lower bound for population density: ")
low = float(low.strip())
up = input(" Enter upper bound for population density: ")
up = float(up.strip())
abc = countryDirectory.populationDensityFilter(low,up)
if len(abc) == 0:
print(" Nothing in that range found.")
else:
print(" Countries with density in this range:")
for x in abc:
print(x[0] + ", " + "density = "+ str(x[1]))
def main():
cd = countryDirectory('data.txt','continent.txt')
testDensityFilter(cd)
main()
解决方案
改变populationDensityFilter
:
results = []
for element in self._catalogue:
pop = self._catalogue[element].getPopulationDensity()
if pop >= min and pop <= max:
results.append((element, pop))
return results
正如你所提到的,
我相信这是因为测试方法需要一个元组,其中包含索引 0 中的国家和索引 1 中的密度。
所以你应该组装一个(country, density)
返回列表。
推荐阅读
- javascript - 浏览器同步不为远程站点注入 CSS
- oauth-2.0 - 如何使用 Firebase 身份验证令牌使用 js 列出用户博客
- list - prolog中相同列表上的两个基于条件的替换函数?
- javascript - React Native:renderItem 组件到 Custom FlatList 作为道具?(如 Vue 插槽)
- r - 如何使用 MCMCregress 命令找到平均值的差异?
- python - 在python中修改struct中的数据
- php - 性能提升:SQLite 和 MYSQL 函数
- python - 如何使用 dask 直接从 s3 存储桶加载和处理许多(>20k).tsv 文件?
- list - Dart:list clear() 函数由于执行顺序而停止添加新元素
- javascript - 使用 Goole Apps 脚本 (GAS) 获取 gmail 电子邮件正文的 getChild