Python中文
首页
教程
问答
标签
搜索
登录
注册
当列表有正确的索引时,我总是在Python中得到“list index out of range”
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我是Python新手,遇到了列表索引错误,而我不应该这样做。 我有以下变量:</p> <pre><code>date_array = ['2001','15','1'] </code></pre> <p>我可以访问第一个索引。我只能访问最后一个索引,如果我尝试这样做:</p> ^{pr2}$ <p>每次尝试时都会出现“列表索引超出范围”错误:</p> <pre><code>date_array[2] date_array[1] </code></pre> <p>我附上以下完整代码供您参考:</p> <pre><code>import csv import datetime import re marketReader = csv.reader(open('test.csv', 'rb')) i=0 for row in marketReader: cust_id = row[0] date = row[1] # Is a text. Ex: '2002-1-1' spent = row[2] date_array = (re.split('-',date)) # Provides an array ['2002', '1', '1'] year = date_array[0] month = date_array[1] day = date_array[2] # Is weekday? weekday=datetime.date(year,month,day).weekday() if i==200 and row[0]>3 : break pass #print(day) i += 1 </code></pre> <p>任何帮助都将非常感谢!这让我发疯了!在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>简单的答案是date_数组并不总是有3个元素。如果要直接索引列表,请添加一个检查以确保长度足够。在</p> <pre><code>if len(date_array) < 3: print('date_array too short') # do something else </code></pre> <p>或者,将索引操作包装在try块中</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何在乒乓球比赛中预测球的轨迹,对于AI球拍预测?
9 回答
如何在乒乓球游戏中阻止球
4 回答
如何在乘法和模中不乘空间?
6 回答
如何在乘法和除以2个不同的数字之间进行交换?
6 回答
如何在也是数据一部分的单个字符上拆分大字符串
8 回答
如何在乾草堆中找到針,有更好的解決方案嗎?
3 回答
如何在事件wxWidgets中传递自定义数据
5 回答
如何在事件中使用lambda i=i?
8 回答
如何在事件中心只接收最近的数据
8 回答
如何在事件发生之前保持云函数运行?
3 回答
如何在事件发生后使页面重定向到同一页面
2 回答
如何在事件回调之间保持python生成器的状态
1 回答
如何在事件处理程序(pythonsocket、sphinx)中保留docstring
4 回答
如何在事件处理程序中更改wxRichTextCtrl的光标位置?
2 回答
如何在事件处理程序中访问外部对象?
1 回答
如何在事件循环中将协程打包为正常函数?
4 回答
如何在事件循环之外运行协同程序?
4 回答
如何在事件循环结束时为并发未来的所有线程调用类方法?
6 回答
如何在事件文件中只保留一份摘要?
5 回答
如何在事件模板中添加事件
7 回答