编写一个函数,子列表,该函数以字符串列表作为参数。在函数中,使用while循环返回输入列表的子列表。子列表应包含与原始列表相同的值,直到达到字符串“ STOP”(不应包含字符串“ STOP”)为止。
def sublist(list):
i = 0
sub = []
while i < len(list):
sub = list
if (sub[i] == 'STOP'):
break
print(sub[i])
i+=1
return sub
答案 0 :(得分:0)
您可以只使用本机方法,以[a:b]作为间隔来仅获取部分列表
def sublist(list):
i = 0
while i < len(list):
if (list[i] == 'STOP'):
return list[0:i]
i+=1
return False
答案 1 :(得分:0)
我以这种方式查看您正在尝试在列表中找到“停止”位置。 我会这样写:
def sublist(string_list):
sub = []
try:
stop_index = next(i for i in range(len(string_list)) if string_list[i] == "STOP")
sub = string_list[:stop_index]
except:
sub = string_list
return sub
您将获得下一站的第一站索引(最快的方式)。 然后,返回原始列表中位于“ STOP”值之前的部分。 如果没有停止,那么您只需发送回原始字符串即可。
您的代码中存在多种误解。 首先,您正在使用while循环迭代i的值。 您应该使用for循环(对于range(len(list))中的i)。
您的行sub = list
将整个“列表”放在sub内。不只是一个要素。您需要使用sub.append(list[i])
来逐个添加元素。
还有其他一些小问题,但我会警告您最后一个问题: 不要使用“列表”作为变量。 list是一个现有的python对象,即list()函数。如果将其用作变量,则会覆盖它,这可能会导致问题。
答案 2 :(得分:0)
我不知道while
循环有多重要,但是有了for
循环,您可以轻松地遍历列表:
def sublist(list):
sub = []
for x in list:
if x != "STOP":
sub.append(x)
else:
break;
return sub
答案 3 :(得分:0)
def sublist (s):
str = []
i = 0
while i<len(s) :
if s[i] == "STOP":
break
str.append(s[i])
i+=1
return str