Python 负列表索引包装为切片

发布于 2024-12-09 12:20:54 字数 413 浏览 1 评论 0原文

我有代表某种表格的嵌套列表。我想访问上面 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空袭的梦i 2024-12-16 12:20:54

由于切片行为内置于 Python 语法中,因此我建议在循环中放置一个简单的“if”语句:

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

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]
美胚控场 2024-12-16 12:20:54

当它尝试打印整行输出时,这会抛出错误

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))

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

如果您不使用 python 3,则可以使用 izip

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文