尝试编写一个小脚本,以便在与仓库接口时让生活更轻松。想要制作一些东西,让我导出一个简单的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时,似乎找不到任何区别。
非常感谢一些帮助!
编辑:
忘记发布引用:)
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
答案 0 :(得分:6)
UPC = UPCget(Style, Color, Size)
这是问题所在。 UPCget
在循环的第一次迭代中正常工作,但UPC
被覆盖。它不再是一个字典,现在它是一个字符串。然后在第二次迭代中它失败了,因为你不能按照UPCget
的方式索引字符串。
尝试使用其他变量名称,这样就不会覆盖原始值。
code = UPCget(Style, Color, Size)
print Color + ', Size ' + Size + ' has UPC code ' + code