发生异常: IndexError
IndexError: list index out of range
具体代码如下:
# 从pyecharts.charts中导入Bar模块
from pyecharts.charts import Bar
# 从collections中导入Counter模块
from collections import Counter
# TODO 从collections中导入OrderedDict模块
from collections import OrderedDict
# 使用with...as语句配合open()函数以r方式,打开路径为“/Users/tongtong/职位数据.txt”的文件,赋值给f
with open(r'C:\Users\31088\Desktop\py数据\职位数据.txt', 'r', encoding='utf-8') as f:
dataList = f.readlines()
# 新建一个字典cityDict
companyDict = {}
# for循环遍历列表dataList中的每个元素data
for data in dataList:
# 如果"薪资面议"在元素中
if "薪资面议" in data:
# 就跳过
continue
# 使用split()以逗号分隔data,索引第2项元素,赋值给company
company = data.split(",")[1]
# 使用split()以逗号分隔data,索引第4项元素,赋值给salary
salary = data.split(",")[3]
# 使用split()以斜杠分隔salary,索引第1项元素,赋值给daily
daily = salary.split("/")[0]
# 使用split()以短横线分隔daily索引第1项,赋值给start
start = daily.split("-")[0]
# 使用split()以短横线分隔daily索引第2项,赋值给end
end = daily.split("-")[1]
# 将start和end转换成整型相加后除以2,并赋值给average
average = (int(start)+int(end))/2
# 如果company不在字典companyDict的键中
if company not in companyDict.keys():
# 将字典中键所对应的值设置为空列表
companyDict[company] = []
# 使用append()函数往字典键所对应的值中添加average
companyDict[company].append(average)
# for循环遍历companyDict.items()中的key,value
for key,value in companyDict.items():
# 使用sum()函数将列表value求和
# 使用len()函数计算列表value长度
# 使用//运算符计算列表value的平均值
average_value = sum(value)//len(value)
# 将字典companyDict的键对应的值设置为average_value
companyDict[key] = average_value
# TODO 使用Counter()函数统计companyDict中的薪资,赋值给salary_counts
salary_counts = Counter(companyDict)
# TODO 使用salary_counts.most_common()计算出现频率最高的7个单词,赋值给top_7_company
top_7_company = salary_counts.most_common(7)
# TODO 使用OrderedDict()函数将top_7_company转换成OrderedDict类型,赋值给sorted_companyDict
sorted_companyDict = OrderedDict(top_7_company)
# TODO 创建Bar对象,赋值给bar
bar = Bar()
# TODO 使用list()将字典sorted_companyDict所有键转换成列表,传入add_xaxis()中
bar.add_xaxis(list(sorted_companyDict.keys()))
# TODO 使用add_yaxis()函数,将数据统称设置为"公司"
# 将字典sorted_companyDict所有值转换成列表,作为参数添加进函数中
bar.add_yaxis("公司",list(sorted_companyDict.values()))
# TODO 使用render()函数存储文件,设置文件名为salary.html
bar.render("salary.html")
报错提示如下:
发生异常: IndexError
list index out of range
File "C:\Users\31088\Desktop\py数据\就业分析.py", line 40, in
end = daily.split("-")[1]
IndexError: list index out of range
如果要访问最后一个元素(倒数第一个),就可使用索引-1,访问倒数第二个元素,可使用-2
例如:要找蔡依林的英文名‘Jolin Tsai’,她是倒数第二个,我们就可以使用索引-2
star_names = ['Jay Chou', 'JJ Lin', 'Jolin Tsai', 'Hannah Quinlivan']
print(star_names[-2])
根据提供的参考资料和问题描述,该错误的原因主要有两个,一个是下标超出range,另一个是list为空。下面是解决方案:
1、先判断索引是否在列表list的范围内,即使用if idx in range(len(test_list))判断。
2、检查是否存在空行或列表为空。
3、使用try...except模块进行异常捕获。
4、检查代码中是否存在超过list最大索引的引用,即判断索引是否越界。
具体解决方案的示例代码如下:
1、判断是否在列表list的范围内:
test_list= ["hello","world","today"] idx = 0 if idx in range(len(test_list)): print(test_list[idx]) else: # 超出list范围 print(f"{idx} exceed list range:{test_list}")
2、检查是否存在空行或列表为空:
if not test_list: print("list is empty")
with open(file_path, 'r') as f: linestr = f.readlines() for s in linestr: if s.strip() == "": print("There is a blank line.")
3、使用try...except模块进行异常捕获:
for s in linestr: try: L = s.split('\t') print(L[0], end=" ") print(isBigGrowth(L, 0.3)) except: print('运行失败')
4、检查代码中是否存在超过list最大索引的引用:
spam = ['cat', 'dog', 'mouse'] print(spam[6]) #越界,会报IndexError: list index out of range错误。
列表索引超出范围
第40行
end = daily.split("-")[1]
daily被分割完可能没是空数组即daily数据可能为空