class IBList:
maxlen = 100 # pre-allocated size of list
def __init__(self):
self.r = 0 # current size of list
self.list = [0] * self.maxlen
如何返回索引r
处的元素,如果r < 0
或r > size - 1
返回字符串“ error”并用索引{{1}处的元素e
替换}并返回要替换的元素?
答案 0 :(得分:0)
您可以使用 len()来获取列表的长度。另外,您可以使用mylist[index] = new_value
替换列表中的值。
def my_func(lst, r, e):
if r < 0 or r > len(lst)-1:
return 'error'
else:
lst[r] = e
return lst[r]
lst = [1, 2, 3, 4, 5]
r = 2
e = 22
print(my_func(lst, r, e))
答案 1 :(得分:0)
这是一个解决方案,将您的问题分为两个单独的功能get_elem
和elem_replace
:
class IBList:
maxlen = 100 # pre-allocated size of list
def __init__(self):
self.r = 0 # current size of list
self.list = [0] * self.maxlen
def get_elem(self,r):
if r >= 0 and r <= len(self.list)-1:
return self.list[r]
else:
return 'error'
def elem_replace(self,r,e):
elem = self.get_elem(r)
if not elem == 'error':
self.list[r] = e
return elem
else:
return None # Handle this case any way you want.