获取超出范围的python列表索引

问题描述 投票:0回答:2

我正在尝试创建过度流动的 pythonic 列表,这意味着如果我试图获取列表的索引,即使索引大于列表大小。

如果索引大于列表大小,我想从列表的开头获取索引。

例如,如果列表大小为 5

l = [1,2,3,4,5] 

所以

l[7]
应该返回
3
[index 2]

谢谢!

python python-3.x list
2个回答
1
投票

您需要使用

%
(取模)运算符来处理这种情况,我假设您的意思是
l[7]
应该返回
3
(在列表中的索引
2
处)。功能解决方案:

def overflow_index(l, idx):
    return l[idx % len(l)]

L = [1, 2, 3, 4, 5]
print(overflow_index(L, 7))  # Output: 3

一个面向对象的解决方案,定义

list
的子类并覆盖其处理下标访问的
__getitem__
方法,即
l[7]

class OverflowList(list):
    def __getitem__(self, idx):
        return super().__getitem__(idx % len(self))


OL = OverflowList([1, 2, 3, 4, 5])
print(OL[7])  # Output: 3

super().__getitem__
函数是指内置
list
的方法,需要调用它来防止无限递归。


1
投票

你的问题不清楚:

假设:

l = [1,2,3,4,5]

l[0] is 1
l[1] is 2
and so on...

你可以做一个

forloop
来打印所有的值:

for x in range(len(l)):
   print(l[x])

现在如果你想在 x 中插入大值,你可以使用

mod operator %

l[x%len(l)]

这里 x 可以是任何大数。

when x=7:

l[7%len(l)]
#output
3

when x=5:

l[5%len(l)]
#output
1
© www.soinside.com 2019 - 2024. All rights reserved.