python - Python 中的循环数组索引

标签 python list

我正在寻找一个圆形的数组(或矩阵),这样

让:

 a = [1,2,3]

那我想

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 1
a[4] = 2

等对于a的所有索引值。

原因是因为我有一个图像作为矩阵,我正在尝试处理它的行为是如果它在一个方向上离开边缘,它应该重新出现在另一侧。

任何有关如何干净地执行此操作的提示都将不胜感激!

最佳答案

你可以像这样使用模运算符

print a[3 % len(a)] 

如果你不想像这样使用模运算符,你需要继承 list 并实现 __getitem__ , 你自己。

class CustomList(list):
    def __getitem__(self, index):
        return super(CustomList, self).__getitem__(index % len(self))

a = CustomList([1, 2, 3])
for index in xrange(5):
    print index, a[index]

输出

0 1
1 2
2 3
3 1
4 2

如果你想对 Numpy 数组做同样的事情,你可以这样做

import numpy as np

class CustomArray(np.ndarray):
    def __new__(cls, *args, **kwargs):
        return np.asarray(args[0]).view(cls)

    def __getitem__(self, index):
        return np.ndarray.__getitem__(self, index % len(self))

a = CustomArray([1, 2, 3])
for index in xrange(5):
    print a[index]

可以找到有关子类化 Numpy 数组的更多信息 here (感谢JonClements)

关于python - Python 中的循环数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808141/

相关文章:

python - 谷歌云 SDK : set environment variable_ python --> linux

python - 无法使用 Python 将数据插入 sqlite3 数据库

python - 列表的哪一端是顶部?

Java列表比较导致错误我无法确定

Python - 输入包含 NaN、无穷大或对于 dtype ('float64' 来说太大的值)

python - 科学刻度标签符号调整

python:根据数据框中的位置对特定行值求和

java - 尝试从 ArrayList 中为每个用户打印出来

c# - 如何在同时删除项目的同时遍历列表?

python - 如果列表中没有则显示/隐藏字段