我正在编写一个函数,它将表示国家名称的字符串作为参数。此函数首先调用前面问题的方法answer来获取国家列表,然后对列表进行二进制搜索,如果找到了国家信息,则打印国家信息。你知道吗
这是第一部分的代码,其中列出了国家:
def readCountries():
open_file = open("countries.txt", 'r')
new_list = []
contents = open_file.readlines()
for i in range(len(contents)):
lsSplit = contents[i].split(",")
new_list.append([lsSplit[0], float(lsSplit[1].strip()), int(lsSplit[2])])
open_file.close()
return new_list
这是我需要帮助的部分:
new_list = readCountries()
def printCountry(name):
lo, hi = 0, len(new_list) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
country = new_list[mid]
test_name = country[0]
if name > test_name:
lo = mid + 1
elif name < test_name:
hi = mid - 1
else:
return country
return countries[lo] if countries[lo][0] == name else None
我从第二部分得到的结果是:
>>> printCountry("Canada")
['Canada', 9976140.0, 35295770]
我怎样才能让它看起来像这样:
>>> printCountry("Canada")
Canada, Area: 9976140.0, Population: 35295770
>>> printCountry("Winterfell")
I'm sorry, could not find Winterfell in the country list.
任何帮助都将不胜感激。你知道吗
试试这个
相关问题 更多 >
编程相关推荐