gpt4 book ai didi

python - 字符串索引必须是整数,而不是 str - Python 脚本

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:05 25 4
gpt4 key购买 nike

尝试编写一个小脚本,让我在与仓库交互时的生活更轻松。想要制作一些东西,让我导出一个简单的 csv 文件,其中包含我需要完成的产品的所有不同样式、尺寸、颜色和 UPC 代码。以下是处理从我创建的字典中获取 UPC 代码的部分代码:

UPC = {'True Premium Flat': {'White': {'6':'994000000446','7':'994000000453','8':'994000000460','9':'994000000477','10':'994000000484','11':'994000000491','12':'994000000507'},
'Silver': {'6':'994000000514','7':'994000000521','8':'994000000538','9':'994000000545','10':'994000000552','11':'994000000569','12':'994000000576'},
'Champagne': {'6':'994000000309','7':'994000000316','8':'994000000323','9':'994000000330','10':'994000000347','11':'994000000354','12':'994000000361'},
'Black': {'6':'994000000378','7':'994000000385','8':'994000000392','9':'994000000408','10':'994000000415','11':'994000000422','12':'994000000439'}
},
'Classic Flat': {'Black': {'Small':'994000000279','Medium':'994000000286','Large':'994000000293'},
'Champagne': {'Small':'994000000248','Medium':'994000000255','Large':'994000000262'},
}
}

def UPCget(St, C, Si):
return UPC[St][C][Si]

LineNum = raw_input('How many different items are returning? ')
Style = raw_input('Style? C or P: ')
if Style == 'C' or Style == 'c':
Style = 'Classic Flat'
if Style == 'P' or Style == 'p':
Style = 'True Premium Flat'
LineNum = int(LineNum)
for num in range(LineNum):
item = num + 1
print('\nItem number ' + str(item))
Color = raw_input('Color: ')
Size = raw_input('Size: ')
UPC = UPCget(Style, Color, Size)
print Color + ', Size ' + Size + ' has UPC code ' + UPC
f.close()

但只有当我的 LineNum 大于 1 时,并且仅在第二次出现时,我才会不断收到“字符串索引必须是整数,而不是 str”错误。我查看了调试器,但似乎找不到我第一次调用 UPCget 与第二次调用 UPCget 之间的任何区别。

非常感谢您的帮助!

编辑:

忘记发布引用:)

How many different items are returning? 2
Style? C or P: P

Item number 1
Color: Silver
Size: 7
Silver, Size 7 has UPC code 994000000521

Item number 2
Color: Champagne
Size: 7

Traceback (most recent call last):
File "/Users/klhuizinga/Documents/Talaria/ASN/UPCget.py", line 26, in <module>
UPC = UPCget(Style, Color, Size)
File "/Users/klhuizinga/Documents/Talaria/ASN/UPCget.py", line 12, in UPCget
return UPC[St][C][Si]
TypeError: string indices must be integers, not str

最佳答案

UPC = UPCget(Style, Color, Size)

问题来了。 UPCget 在循环的第一次迭代中工作正常,但随后 UPC 被覆盖。它不再是字典,现在是字符串。然后在第二次迭代中它失败了,因为你不能像 UPCget 那样索引一个字符串。

尝试使用不同的变量名称,以免覆盖原始值。

code = UPCget(Style, Color, Size)
print Color + ', Size ' + Size + ' has UPC code ' + code

关于python - 字符串索引必须是整数,而不是 str - Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38443980/

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