开发者

Python negative list indices wrapped as slicing

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 o开发者_运维知识库r that something is triggered my program could react to.

Any thoughts?


Since the slicing behavior is built in to the Python syntax, I'd recommend putting a simple 'if' statement in your loop:

for k in [-1, 0, 1]:
    idx = i+k
    if idx < 0: raise IndexError, 'list index is out of range'
    print lists[idx][0]


This will throw an error when it tries to print an entire row

lists = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
merged=zip(*lists)
keys=[-1,0,1]
row=merged[0]
for i,_ in enumerate(row):
        print " ".join((str(row[k+i]) for k in keys))

output:

11 1 6
1 6 11
Traceback (most recent call last):
  File "asdf.py", line 6, in <module>
    print " ".join((str(row[k+i]) for k in keys))
  File "asdf.py", line 6, in <genexpr>
    print " ".join((str(row[k+i]) for k in keys))
IndexError: tuple index out of range

you could use izip if you're not using python 3

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜