繁体   English   中英

python增加了字典问题

[英]Having adding to dictionary problems python

这是我的代码的一部分:

add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for each in add_values:
    print(each)
    s=add_values[each]
    s=int(s)
    h=s*100
    mydict[add_values[each]]=s

它带来了这个错误:

IndexError: list index out of range 
(For the s=add_values[each] line)

请您告诉您这里出了什么问题以及需要更改的内容,

谢谢。

考虑达到add_values的第五项:

for each in add_values: 
    print(each) # each == 50
    s=add_values[each] # what's the fiftieth item in 'add_values'?!

你不需要索引add_values ,你已经访问值-取代add_values[each]用,简单地说, each

each都是值,您不能将其用作索引(主要是因为add_values的大小为14,并且在add_values内部具有大于此值的值):

add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for each in add_values:
    print(each)
    s=each
    s=int(s)
    h=s*100
    mydict[each]=s

另一种解决方案是使用索引:

add_values=[2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for i in range(len(add_values)):
    print(add_values[i])
    s=add_values[i]
    s=int(s)
    h=s*100
    mydict[add_values[i]]=s

您正在使用数组元素作为数组索引 ,这就是为什么出现越界错误的原因。

使用Python的for循环符号,您无需显式访问索引; 只需访问该元素,在您的情况下就是each

for each in add_values:
    print(each)
    s=each              # kind of redundant, but this should work

for each in add_value将其each设置for each in add_value等。在循环的第4次迭代中, each add_values[each]均为20。当您说add_values[each] ,您会收到错误消息,因为add_values仅包含14个元素,并且您尝试访问20号元素。如果尝试访问50000号元素,您将遇到更多麻烦。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM