Py学习  »  Python

如何定义python列表循环迭代时结束的条件?[暂时搁置]

Timothy Lombard • 5 年前 • 1648 次点击  

我遇到了这个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))
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43506
 
1648 次点击  
文章 [ 2 ]  |  最新文章 5 年前