我一直在尝试找出使用户输入指定键以输出其相应值的方法。我不确定我是否正确设置了字典。我必须定义一个带有附加文本文件的字典,并且在该文本文件中,每行都有一个国家名称,空格和收入,看起来像这样-“卡塔尔$ 129,700”。
我的问题是,如何到达可以输入国家名称的地方并输出正确的收入值?
当前代码:
import string
import re
import fileinput
infile = open("C:\\Users\\mrbal\\Desktop\\Homework
Assignments\\percapita.txt", "r")
dict1 = {}
for line in infile:
x = line.split(" ")
countryName = x[0]
income = x[1]
print(countryName, income)
print("##############################")
#country = input("Please enter the desired country: ")
首先,我是否正确设置了词典?
其次,在当前的设置中,当我运行程序时,它会输出文件的内容,这很好,但是我仍然需要用户从字典中输入国家/地区,然后输出其值。我将如何去做?
您可以在代码中进行一些改进:
您没有用值初始化字典,请执行。
您可以使用类似PEP的变量名country_name
代替countryName
您打开文件但不关闭它。使用with
避免这种情况。
因此,代码变为:
import string
import re
import fileinput
with open("C:\\Users\\mrbal\\Desktop\\Homework Assignments\\percapita.txt", "r") as infile:
incomes = {}
for line in infile:
x = line.split(" ")
country_name, income = x[0], x[1]
print(country_name, income)
incomes[country_name] = income
print("##############################")
country = input("Please enter the desired country: ")
print(incomes.get(country, "No information found for country %s" % country))
如果要向用户提供国家/地区列表,只需添加其他打印声明:
print("Options for country are: %s" % incomes.keys())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句