[英]How can I fix this error in python 3.4 tkinter “Index Error: list index out of range”
[英]Python 3.4 - List index out of range error occurs when running script, but not in interpreter
考虑下面的列表,我将innerlist
列表称为innerlist
:
['66957039892995', '-70', '-70', '-70', '1', '1', '0', '']
我正在尝试使用上面的列表制作字典。 当我在Python解释器中手动执行此操作时,它可以正常工作。
datadict = {
'a': innerlist[0],
'b': innerlist[1],
'c': innerlist[2],
'd': innerlist[3],
'e': innerlist[4],
'f': innerlist[5],
'g': innerlist[6],
'h': "not available" if not innerlist[7] else innerlist[7]
}
在解释器中,它使字典没有任何错误。 当我找出列表的长度时,输出8。
但是,当我尝试在脚本中运行此代码时,Pycharm会引发以下错误:
File "**hidden filepath**", line 25, in make_wd
'h': "not available" if not innerlist[7] else innerlist[7]
IndexError: list index out of range
编辑 :脚本:
import pymongo
from pymongo import MongoClient
def make_wd(innerlist):
datadict = {
'a': innerlist[0],
'b': innerlist[1],
'c': innerlist[2],
'd': innerlist[3],
'e': innerlist[4],
'f': innerlist[5],
'g': innerlist[6],
'h': "not available" if not innerlist[7] else innerlist[7]
}
return datadict
if __name__ == '__main__':
try:
client = MongoClient()
except :
print("Could not connect to MongoDB")
db = client.testdb
innerlist = ['66957039892995', '-70', '-70', '-70', '1', '1', '0', '']
testdict = make_wd(innerlist)
db.testcollection.insert_one(testdict)
使用ipdb放置断点,并在运行脚本时检查列表中实际包含的内容
您可以通过安装pip install ipdb
并尝试在dict创建之前设置断点
import ipdb;ipdb.set_trace()
对于没有第7个索引的情况,应尝试使用
if len(your_list)>7 and your_list[7]:
data = your_list[7]
else:
data = "Not Available"
并使用数据分配“ h”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.