Movatterモバイル変換


[0]ホーム

URL:


Built-in func to calculate negative indices??

Eddie and Babskca17 at dial.pipex.com
Tue Apr 17 14:49:42 EDT 2001


Do we want a built-in function to calculate the absolute (ie, positive) values of negative subscript indices? For example:-x = "python"x[-2]        # = "o"; positive index = 4pos = absIndex(len(x), -2)    # pos = 4x[pos]        # = "o"The "absIndex" function would have the semantics of the following Pythonfunction:-    def absIndex(index, size):        if index >= 0:            result = index        elif index < 0:            result = index + size        if (result < 0) or (result >= size):            return None        # ie, invalid result        else:            return resultIt would be possible to constrain the return value to something between 0and size - 1 within the function (using min and max), but this would make ithard to spot index errors. You would, however, want to constrain the returnvalue when dealing with slices, so perhaps a separate "absSlice" would beuseful as well.Of course it is very easy to implement these functions yourself in Python,but I bet this same code is written over and over again by peoplere-defining the subscript operators. Built-in functions might make the codea bit more standard and self-documenting.&.


More information about the Python-listmailing list

[8]ページ先頭

©2009-2025 Movatter.jp