0

我有一个像这样设置的字典 {'USA': ('123456', '456020832'), ... }

关键显然是国家,另外两个是面积(英里)和人口。我需要帮助尝试将区域和人口转换为 int。(它们现在是字符串)。

这就是我所拥有的:

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]] = (row[1].replace(',', ''), row[2].replace(',', '')) 
        #i have tried countries[row[0]] = int((row[1].replace(',', '')), int(row[2].replace(',', '')) ) with no luck 
    reply = choicebox(msg=msg2, choices= list(countries.keys()) )
    writeln(reply + "-\tArea: " + (countries[reply])[0] + "\tPopulation: " + (countries[reply])[1] )

谢谢!我只是不断收到有关转换的错误,所以我正在寻求帮助

4

1 回答 1

1

阅读时将您的代码更改为:

countries[row[0]] = int(row[1].replace(',', '')), int(row[2].replace(',', ''))

或者,或者,一个你以后如何做的例子:

d = {'USA': ('123456', '456020832'), 'UK': ('12345', '9876544')}
for k, v in d.iteritems():
    d[k] = tuple(int(el) for el in v)
# {'UK': (12345, 9876544), 'USA': (123456, 456020832)}

调试你的ValueError

将您的代码修改为如下所示:

for row in reader:
    try:
        countries[row[0]] = int(row[1].replace(',', '')), int(row[2].replace(',', ''))
    except ValueError as e:
        print(row)

这将捕获TypeError并打印到控制台失败的行。然后,您可以查看这些内容并确定您的列未成功转换为int.

于 2013-02-27T04:22:28.560 回答