简体   繁体   English

有效地用半值索引 numpy 数组

[英]Indexing numpy array with half-values efficiently

I would like to index a numpy array with integer and half values.我想用整数和半值索引一个 numpy 数组。 This is roughly what I have in mind:这大致是我的想法:

>>> a = HalfIndexedArray([[0,1,2,3],[10,11,12,13],[20,21,22,23]])
>>> print(a[0,0])
0
>>> print(a[0.5,0.5])
11
>>> print(a[0,1+0.5])
3

Only half-values would be used as indices, so I imagine some kind of wrapper could be constructed that stores the values at integer indices that are accessed by multiplying the given fractional index.只有半值用作索引,所以我想可以构造某种包装器,将值存储在整数索引处,通过乘以给定的小数索引来访问这些值。

One could construct some kind of helper function that can get and set the values accordingly;可以构造某种辅助函数来获取和设置相应的值; however, it would be even better if the native numpy indexing functionality (slices etc.) could be still used.但是,如果仍然可以使用本机 numpy 索引功能(切片等),那就更好了。 Additionally, significant overhead is not really acceptable, as these arrays would be used for numerical computations.此外,显着的开销是不可接受的,因为这些数组将用于数值计算。

It is basically some efficient syntactic sugar that I am looking for: is this something that can be achieved in numpy (or more broadly, in Python)?它基本上是我正在寻找的一些有效的语法糖:这是可以在 numpy(或更广泛地说,在 Python)中实现的吗?

My recommendation would be that instead of creating a separate class to account for half-integer indexing, just handle it on the input side.我的建议是,与其创建一个单独的类来解释半整数索引,不如在输入端处理它。 If you take a half-integer index system and multiply your input by two, you can translate that trivially to a normal integer index.如果您采用半整数索引系统并将输入乘以 2,则可以将其简单地转换为普通整数索引。

This would likely result in a cleaner and easier to upkeep piece of code.这可能会导致代码更清晰、更容易维护。

However, if you want to go ahead and create a custom iterable, this could be helpful: https://thispointer.com/python-how-to-make-a-class-iterable-create-iterator-class-for-it/但是,如果您想继续创建自定义迭代,这可能会有所帮助: https ://thispointer.com/python-how-to-make-a-class-iterable-create-iterator-class-for-it /

In order to change behavior of [] you need to reimplement __getitem__ class method.为了改变[]的行为,您需要重新实现__getitem__类方法。 Since your class would behave as a standard list otherwise, you can do this:由于您的课程在其他情况下将表现为标准列表,因此您可以这样做:

class HalfIndexedList(list):
    def __getitem__(self, key):
        return super().__getitem__(int(key * 2))

a = HalfIndexedList([10,11,12,13,14,15])
for i in range(0, 6):
    print(f"{i/2 = }, {a[i/2] = }") 

However, I agree with @Otto answer and the statement that it's much better to handle that input-side for cleaner code.但是,我同意@Otto 的回答以及处理输入端以获得更简洁的代码要好得多的说法。 Half-indexing doesn't make sense and is really unintuitive.半索引没有意义,而且非常不直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM