2015-05-22 96 views
1

我遇到问题,将一些数字从字符串转换为整数。这是有问题的功能:将字典值转换为整数

def read_discounts(): 
    myFile = open('discount.txt', 'r') 
    discountValues = {} 

    #read and split first line 
    firstLine = myFile.readline() 
    firstLine = re.sub(r'\$','',firstLine) 
    firstLine = re.sub(r'\%','',firstLine) 
    firstLine = firstLine.split() 

    #add values to dictionary 
    discountValues['UpperLimit1'] = {firstLine[2]} 
    int(discountValues['UpperLimit1']) 
    discountValues['PercentDiscount1'] = {firstLine[4]} 

而且回溯:

Traceback (most recent call last): 
File "C:\Users\Sam\Desktop\test.py", line 94, in <module> 
main() 
File "C:\Users\Sam\Desktop\test.py", line 6, in main 
discounts = read_discounts() 
File "C:\Users\Sam\Desktop\test.py", line 33, in read_discounts 
int(discountValues['UpperLimit1']) 
TypeError: int() argument must be a string or a number, not 'set' 

我稍微超出我的深度,但我知道,discountValues['UpperLimit']是应该能够被转换为一个值整数(100

我试过了:我已经尝试将字符串列表中的值转换为字典之前的值,并且我得到了相同的结果。我也尝试过使用词典理解,但是当我稍后使用该值时似乎会导致问题。

任何意见将不胜感激,谢谢。

+0

取出围绕第一行的{和} [] – NendoTaka

+3

将错误整理出来后,可能值得注意的是int(discountValues ['UpperLimit1'])'没有任何作用。 'int(somevalue)'不会将'somevalue'转换为int中的int值;你需要'somevalue = int(somevalue)'。 – Kevin

+0

谢谢都。特别是凯文,真的救了我。 – c3066521

回答

2

您正在以错误的方式分配字典值。它应该是

discountValues['UpperLimit1'] = firstLine[2] # Droped the { and } from assignment 
int(discountValues['UpperLimit1']) 
discountValues['PercentDiscount1'] = firstLine[4] 

包木窗了事情{}将创建sets in python3

测试

>>> a_dict = {} 
>>> a_dict["set"] = {"1"} # creates a set and assign it to a_dict["set"] 
>>> type(a_dict["set"]) 
<class 'set'> 
>>> a_dict["string"] = "1" # Here a string value is assigned to a_dict["string"] 

>>> type(a_dict["string"]) 
<class 'str'> 

>>> int(a_dict["string"]) 
1 
>>> int(a_dict["set"]) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set' 

编辑

如果你想整数值分配给字典键,它必须在转让时间,因为你加在你firstLine[2]它使一组{}做过类似

discountValues['UpperLimit1'] = int(firstLine[2]) # int() converts string to int 
discountValues['PercentDiscount1'] = int(firstLine[4]) 
+0

如果downvoter会指出答案的错误,那将非常有帮助。谢谢 – nu11p01n73R

+0

感谢您的回复。我纠正了字典值的分配。现在没有错误,但字典值似乎仍然是一个字符串。任何想法我在这里做错了吗? – c3066521

+0

这是因为你只说'int(discountValues ['UpperLimit1'])'而不是'discountValues ['UpperLimit1'] = int(discountValues ['UpperLimit1'])''。 int()调用返回一个值 - 它不会原地修改传递的对象。 – TigerhawkT3

2

。如果你删除{}它应该工作。

同样如上述注释之一,您实际上需要在将其保存为int后保存该值。只需拨打int(discountValues['UpperLimit1'])就不会实际保存号码。如果你想让你的字典有整数而不是字符串,试试类似discountValues['UpperLimit1'] = int(firstLine[2])