使用While循环列出索引超出范围

时间:2019-01-08 14:02:01

标签: python

这是我的第一次发布,我是新手,所以请原谅我的问题中的任何错误。我必须创建一个使用While循环并接收数字列表并将每个数字添加到新列表中的函数,直到达到特定数字为止。例如-我希望添加列表中的每个数字,直到列表中的数字达到5。如果数字5不在列表中,那么我将按原样获得整个列表。我遇到的问题是最后一部分。我下面发布的当前代码可以给我一个新的数字列表,该列表以数字5停止,但是当数字5不包括在列表中时,出现“列表索引超出范围”错误。我确信这是我不应该考虑的小问题。对于我在做错事的任何帮助或指导,将不胜感激。

def sublist(x):
    i = 0
    num_list = []
    while x[i] != 5:
        num_list.append(x[i])
        i = i + 1
    return num_list

print(sublist([1, 2, 5, 7])) #works fine
print(sublist([1, 2, 7, 9])) #list index out of range error

4 个答案:

答案 0 :(得分:1)

正如其他人指出的那样,最好在知道所需的数字循环(例如您的情况下为for)时使用len(x)循环。

如果您仍然真的想使用while循环,则需要检查每个循环以查看是否检查了旧列表中的每个项目,然后退出。如果您使用while循环,则代码如下所示:

def sublist(x):
    i = 0
    num_list = []
    original_length = len(x)
    while i < original_length and x[i] != 5:
        num_list.append(x[i])
        i = i + 1
    return num_list

print(sublist([1, 2, 5, 7])) #works fine
print(sublist([1, 2, 7, 9])) #now also works fine

编辑:我最初在循环内检查i < original_length,将其更改为在while条件内。但请务必谨慎,因为支票必须在x[i] != 5之前。我的意思是使用它会起作用:

while i < original_length and x[i] != 5:

但这不会:

while x[i] != 5 and i < original_length:

答案 1 :(得分:0)

这应该可以解决问题。如果n(在您的示例中为5)在列表x中,则它将一直使用该列表。否则,它将占据整个列表。不过,这不是最pythonic的选项。也许有人知道更好的方法。

def sublist(x, n):
    num_list=[]
    if n in x:
        for i in x:
            while i!=n:
                num_list.append(i)
    else:
        num_list=x
    return num_list

答案 2 :(得分:0)

如果列表中没有5,则循环不会停止,因此索引i等于x的长度(x的长度为发生错误时在迭代中超出范围。

使用python循环时,最好使用for in循环:

def sublist(x):
  num_list = []
  for n in x:
    if n != 5:
      num_list.append(n)
    else:
      break
  return num_list

print(sublist([1, 2, 5, 7])) # [1, 2]
print(sublist([1, 2, 7, 9])) # [1, 2, 7, 9]

答案 3 :(得分:0)

尝试一下

def sublist(x):
    x.sort() 
    limit_num = 5
    if limit_num not in x:return x
    return x[:x.index(limit_num)]

print(sublist([1, 2, 5, 7]))
print(sublist([1, 2, 7, 9])) 

Result:[1, 2]
       [1, 2, 7, 9]