Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何停止在列表中放置元素_Python_Loops_Iteration_Next - Fatal编程技术网

Python 如何停止在列表中放置元素

Python 如何停止在列表中放置元素,python,loops,iteration,next,Python,Loops,Iteration,Next,我希望te创建一个函数,将元素添加到列表中。我希望它在到达范围边界时停止() 我明白了: def get_values(i,n): d =[] for x in range(n): d.append(next(i)) return d i = iter(range(10)) print((get_values(i,5))) print((get_values(i,4))) print((get_values(i,2))) It gives me: [0, 1, 2,

我希望te创建一个函数,将元素添加到列表中。我希望它在到达范围边界时停止() 我明白了:

def get_values(i,n):
  d =[]
  for x in range(n):
      d.append(next(i))
  return d

i = iter(range(10))

print((get_values(i,5)))
print((get_values(i,4)))
print((get_values(i,2)))

It gives me:
[0, 1, 2, 3, 4]
[5, 6, 7, 8]
Traceback (most recent call last):
  File "/Users/user/Documents/untitled1/lol.py", line 17, in <module>
    print((get_values(i,2)))
  File "/Users/user/Documents/untitled1/lol.py", line 4, in get_values
    d.append(next(i))
StopIteration

我如何控制循环以仅放置I的range()中的元素?

只需倾听错误并在出现错误时停止迭代并中断循环:

def get_values(i,n):
  d =[]
  for x in range(n):
      try:
          d.append(next(i))
      except StopIteration:
          break
  return d

检查是否可以继续的唯一方法是收听
StopIteration
异常。下面是另一个我认为很方便的解决方案:

def get_值(i,n):
d=[]
尝试:
对于范围内的u(n):
d、 附加(下一(i))
最后:
返回d
查找以了解有关可以传递到下一个语句的参数的更多信息

def get_values(i,n):
  d =[]
  for x in range(n):
      temp=next(i,'end')
      if temp=="end":
          break
      d.append(temp)
      
  return d
i = iter(range(10))

print((get_values(i,5)))
print((get_values(i,4)))
print((get_values(i,2)))
输出

[0, 1, 2, 3, 4]
[5, 6, 7, 8]
[9]
如果出现错误,你预计会发生什么?不管怎样,在这里,您通常只需处理错误,使用
try-except StopIteration
,并根据需要处理该错误(引发另一个错误,简单地终止函数,等等)。注意,这里您基本上是在重新发明
itertools.islice
,您可以使用它,即
list(itertools.islice(i,5))
或其他任何东西
[0, 1, 2, 3, 4]
[5, 6, 7, 8]
[9]