0

有什么办法可以在读入这个字典时将每个键值的值转换为 int?最初它们是字符串,但我希望它们是整数。这是我尝试过的,但我遇到了错误!每个键看起来像 {'USA': ('123,123', '312,321,321')} 但我希望这些数字是整数

**def _demo_fileopenbox():        
msg  = "Pick A File!"
msg2 = "Select a country to learn more about!"
title = "Open files"
default="*.py"
f = fileopenbox(msg,title,default=default)
writeln("You chose to open file: %s" % f)

countries = {}

with open(f,'r') as handle:
    reader = csv.reader(handle, delimiter = '\t')  
    for row in reader:
        countries[row[0]] = ((int(row[1])),(int(row[2])))
    while 1:
        reply = choicebox(msg=msg2, choices= list(countries.keys()) )
        writeln(reply + ";\tArea: " + (countries[reply])[0] + "\tPopulation: " + (countries[reply])[1] )
  **

谢谢!

4

2 回答 2

2

int在将它们转换为s之前尝试从字符串中删除逗号:

countries[row[0]] = (int(row[1].replace(',', '')), int(row[2].replace(',', '')))
于 2013-02-26T23:57:37.020 回答
0

您的问题是您的数字包含逗号。将代码更改为:

for row in reader:
    countries[row[0]] = tuple(int(a.replace(",","")) for a in row[1:])
于 2013-02-26T23:58:32.940 回答