我创建了一个从列表中获取指定切片的函数。
def get_slice(my_list, start, stop):
new_list = []
length = 0
for x in my_list:
length = length + 1
if stop > length:
stop = length
start = start - 1
for x in range(start, stop):
x = my_list[x]
new_list.append(x)
elif start > length or start < 1:
return new_list
elif start > stop:
return new_list
else:
start = start - 1
for x in range(start, stop):
x = my_list[x]
new_list.append(x)
print(new_list)
输入为以下内容时,一切正常:
get_slice(['r', 'i', 'g'], 0, 4)
看代码,我不明白为什么。如果给出了以上输入,则输出应该是一个空列表,并且我创建了一个elif来覆盖起始值是否小于1,然后应该返回一个空列表。
我希望能有新的眼光帮助我找出问题所在。
在一组if / elif / else语句中,它将仅评估第一个为true的语句。
在这种情况下,第一个为真的if stop > length:
场景是第一个场景。您可以使条件变得更加复杂,也可以使对无效方案的检查成为第一个方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句