Python 负列表索引包装为切片
我有代表某种表格的嵌套列表。我想访问上面 n 行中的元素。这很容易,但是,我的问题是我想捕捉桌子之外的任何东西并对其做出反应。但在这种情况下,afaics 负指数被解释为切片并被“包裹”。
这是一个例子:
lists = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
for i in range(len(lists)):
for k in [-1,0,1]:
print, lists[i+k][0]
print
11 1 6
1 6 11
6 11
IndexError: list index out of range
我想要的是第一个调用也抛出一个 IndexError ,或者触发我的程序可以做出反应的东西。
有什么想法吗?
I have nested lists that represents a table of sorts. I would like to access the element in n rows above. That it is easy, however, my problem is that I would like to catch anything that is outside the table and react to it. But afaics negative indices get interpreted as slicing in this case and get "wrapped around".
Here is an example:
lists = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
for i in range(len(lists)):
for k in [-1,0,1]:
print, lists[i+k][0]
print
11 1 6
1 6 11
6 11
IndexError: list index out of range
What I would like to to have is that the first call throws an IndexError as well or that something is triggered my program could react to.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于切片行为内置于 Python 语法中,因此我建议在循环中放置一个简单的“if”语句:
Since the slicing behavior is built in to the Python syntax, I'd recommend putting a simple 'if' statement in your loop:
当它尝试打印整行输出时,这会抛出错误
:
如果您不使用 python 3,则可以使用 izip
This will throw an error when it tries to print an entire row
output:
you could use izip if you're not using python 3