gpt4 book ai didi

python - 将字典值转换为整数

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:14 26 4
gpt4 key购买 nike

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

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)

我尝试过的: 我尝试在将字符串列表中的值添加到字典之前对其进行转换,但我得到了相同的结果。我也尝试过使用字典理解,但是当我稍后使用该值时,这似乎会导致问题。

如有任何建议,我们将不胜感激,谢谢。

最佳答案

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

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'

编辑

如果您尝试将整数值分配给字典键,则必须在分配时完成,例如

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

关于python - 将字典值转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com