【问题标题】:change input into int while its being placed into dictionary在将输入放入字典时将输入更改为 int
【发布时间】:2013-02-12 15:35:02
【问题描述】:

在读入这个字典时,有什么方法可以将每个键值的值转换为 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] )
  **

谢谢!

【问题讨论】:

  • 您是否尝试在转换前删除逗号?
  • 有没有办法在它被读取时做到这一点?
  • 有,看我的回答。

标签: python csv converter


【解决方案1】:

在将字符串转换为ints 之前尝试从字符串中删除逗号:

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

【讨论】:

  • 感谢您的帮助,但是当我这样做时,我得到了这个错误?有什么想法吗? **国家[row[0]] = (int(row[1].replace(',', '')), int(row[2].replace(',', ''))) ValueError: 无效以 10 为底的 int() 的文字:''**
  • 这意味着这些单元格中还有其他非数字字符。在该行之前插入一个print row,看看你得到了什么。
  • 哦,我认为数字末尾有空格。任何摆脱这些的方法。它只是文本最初分隔的方式
  • 空格不应破坏int()。错误之前打印的最后一行是什么?
  • 如果我去掉 int 部分,这是一个输出样本,如果我只是打印(国家):{'France': ('211208', '64057792'), 'Kazakhstan': ( '1049150', '15399437'), 'Vanuatu': ('4710', '218519')..... 所以删除逗号是有效的,但它不会转换为 int
【解决方案2】:

您的问题是您的数字包含逗号。把代码改成这样:

for row in reader:
    countries[row[0]] = tuple(int(a.replace(",","")) for a in row[1:])

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2011-04-13
    • 1970-01-01
    • 2022-10-24
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多