我遇到了这个python实践问题:
编写一个函数sublist,它接受一个数字列表作为参数。在函数中,使用while循环返回输入列表的子列表。子列表应该包含与原始列表相同的值,直到它达到数字5为止(它不应该包含数字5)。
这是我的尝试,但你是有效的永远不会被设置为假。
def sublist(lst):
is_valid = True
ret_lst = []
while is_valid:
for x in lst:
print(x, is_valid)
if x == 5:
is_valid == False
else:
ret_lst.append(x)
return ret_lst
lst = [1,2,3,4,5]
print(sublist(lst))
阅读完评论后,我将函数重写为:
def sublist(lst):
ret_lst = []
i = 0;
while i < len(lst):
if lst[i] != 5:
ret_lst.append(lst[i])
i += 1
else:
break
return ret_lst
lst = [1,2,3,4,5,7,9]
print(sublist(lst))