【发布时间】:2015-11-16 01:44:23
【问题描述】:
我有这个代码
def readCountries(self):
countryList = []
with open('countries.txt', 'r') as countryText:
for line in open('countries.txt', 'r'):
countries = countryText.read()
countryList.append(line.strip().split())
return countryList
他的代码像这样输出countries.txt:
[["阿富汗",647500.0,25500100],["阿尔巴尼亚",28748.0,2821977],...,["津巴布韦",390580.0,12973808]]
它是[name, area, population]。我想要做的是编写一个函数,调用上面代码中的答案来获取国家列表并进行二进制搜索并在找到时打印国家信息。示例:
printCountry("Canada")
Canada, Area: 9976140.0, Population: 35295770
printCountry("Winterfell")
I'm sorry, could not find Winterfell in the country list.
我不知道如何做这部分,感谢任何帮助。
【问题讨论】:
-
如果你只是想找国家,又不想自己实现二分查找,python提供了一个二分查找的bisect库。
-
您是否考虑过使用va 字典而不是列表?这似乎是您应该使用它们的典型场景。
标签: python binary-search