我正在尝试利用 NumPy 完成数组支持列表的构建。这种特殊的方法给我带来了麻烦,我无法诊断问题。
def index(self, value, i=0, j=None):
"""Returns the index of the first instance of value encountered in
this list between index i (inclusive) and j (exclusive). If j is not
specified, search through the end of the list for value. If value
is not in the list, raise a ValueError."""
if j is None:
j = self.size
for idx in range(i, j):
if self.data[idx] == value:
return idx
raise ValueError()
这是测试返回的内容:
self = [1, 2, 1, 2, 1, 1, 1, 2, 1], value = 2, i = 4, j = -1
def index(self, value, i=0, j=None):
if j is None:
j = self.size
for idx in range(i, j):
if self.data[idx] == value:
return idx
> raise ValueError()
E ValueError
arraylist.py:168: ValueError
def getindex(lst, value, i=0, j=None):
#define j if j is None or j == -1
j = len(lst)-1 if j == -1 or j is None else j
#create a list with the value from i and j
l = [lst[k] for k in range(i, j)]
try:
# get the index of the value
idx = l.index(value)
# Add i as you want to know the index in the original list
idx = idx + i
return idx
except ValueError:
return 'Value Error'
#for given values
lst = [1, 2, 1, 2, 1, 1, 1, 2, 1]
value = 2
i = 4
j = -1
r = getindex(lst,value, i)
print(r) # output : 7
#If j is not specified
lst = [1, 2, 1, 2, 1, 1, 1, 2, 1]
value = 2
i = 4
r = getindex(lst,value, i)
print(r) # output : 7
# If value not in the given lst
lst = [1, 2, 1, 2, 1, 1, 1, 4, 1]
value = 2
i = 4
r = getindex(lst,value, i)
print(r) #output: Value Error