在这段代码中,为什么使用'for'会导致没有'StopIteration'或'for'循环捕获所有异常然后以静默方式退出?在这种情况下,为什么我们有无关的"回归"?或者是
for由:StopIteration?
#!/usr/bin/python3.1
def countdown(n):
print("counting down")
while n >= 9:
yield n
n -= 1
return
for x in countdown(10):
print(x)
c = countdown(10)
next(c)
next(c)
next(c)
Run Code Online (Sandbox Code Playgroud)
假设for是由以下方式触发:return.GeneratorExit何时生成?
def countdown(n):
print("Counting down from %d" % n)
try:
while n > 0:
yield n
n = n - 1
except GeneratorExit:
print("Only made it to %d" % n)
Run Code Online (Sandbox Code Playgroud)
如果我手动执行:
c = countdown(10)
c.close() #generates GeneratorExit??
Run Code Online (Sandbox Code Playgroud)
在哪种情况下,为什么我看不到追溯?
我正在使用生成器在列表中执行搜索,就像这个简单的例子:
>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3
Run Code Online (Sandbox Code Playgroud)
(只是为了对示例进行框架化,我使用的列表与上面的列表相比要长得多,而且条目有点复杂int.我这样做,所以每次我都不会遍历整个列表搜索他们)
现在如果我改为那样i == 666,它会返回一个,StopIteration因为它找不到任何666条目a.
我怎样才能让它返回None?我当然可以将它包装在一个try ... except子句中,但有更多的pythonic方法吗?
我很好奇使用raise StopIteration和return生成器中的语句之间的区别.
例如,这两个函数之间有什么区别吗?
def my_generator0(n):
for i in range(n):
yield i
if i >= 5:
return
def my_generator1(n):
for i in range(n):
yield i
if i >= 5:
raise StopIteration
Run Code Online (Sandbox Code Playgroud)
我猜的更"Python化"的方式来做到这一点是第二种方式(请纠正我,如果我错了),但据我可以看到两种方式提出一个StopIteration例外.
我正在尝试运行此代码:
import web
urls = (
'/', 'index'
)
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
Run Code Online (Sandbox Code Playgroud)
但它每次都给我这个错误
C:\Users\aidke\Desktop>python app.py
Traceback (most recent call last):
File "C:\Users\aidke\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\utils.py", line 526, in take
yield next(seq)
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "app.py", line 14, in <module>
app = web.application(urls, globals())
File "C:\Users\aidke\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\application.py", line 62, in __init__
self.init_mapping(mapping)
File "C:\Users\aidke\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\application.py", line 130, in init_mapping
self.mapping = list(utils.group(mapping, 2))
File "C:\Users\aidke\AppData\Local\Programs\Python\Python37-32\lib\site-packages\web\utils.py", …Run Code Online (Sandbox Code Playgroud) 为什么在示例函数中终止:
def func(iterable):
while True:
val = next(iterable)
yield val
Run Code Online (Sandbox Code Playgroud)
但如果我脱掉yield语句函数会引发StopIteration异常吗?
编辑:很抱歉误导你们.我知道什么是发电机以及如何使用它们.当然,当我说功能终止时,我并不意味着急切的功能评估.我只是暗示当我使用函数生成生成器时:
gen = func(iterable)
Run Code Online (Sandbox Code Playgroud)
在func的情况下它工作并返回相同的生成器,但在func2的情况下:
def func2(iterable):
while True:
val = next(iterable)
Run Code Online (Sandbox Code Playgroud)
它引发StopIteration而不是None返回或无限循环.
让我更具体一点.itertools中有一个函数tee,相当于:
def tee(iterable, n=2):
it = iter(iterable)
deques = [collections.deque() for i in range(n)]
def gen(mydeque):
while True:
if not mydeque: # when the local deque is empty
newval = next(it) # fetch a new value and
for d in deques: # load it to all the …Run Code Online (Sandbox Code Playgroud) 我有一个生成器,我想在实际内容中添加一个初始值和最终值,它是这样的:
# any generic queue where i would like to get something from
q = Queue()
def gen( header='something', footer='anything' ):
# initial value header
yield header
for c in count():
# get from the queue
i = q.get()
# if we don't have any more data from the queue, spit out the footer and stop
if i == None:
yield footer
raise StopIteration
else:
yield i
Run Code Online (Sandbox Code Playgroud)
当然,上面的代码不起作用 - 我的问题是我希望这样当队列中没有任何东西时,我希望生成器吐出footerAND引发StopIterator.有任何想法吗?
干杯,
我想从csv文件中读取最多20行:
rows = [csvreader.next() for i in range(20)]
Run Code Online (Sandbox Code Playgroud)
如果文件有20行或更多行,则工作正常,否则失败并出现StopIteration异常.
有没有一种优雅的方法来处理迭代器,它可以在列表解析中抛出StopIteration异常,还是应该使用常规for循环?
我有一行从多个列表中提取变量,我希望它避免出现StopIteration错误,以便它可以移动到下一行.目前我正在使用break函数,这避免了StopIteration,但只给了我列表中的第一项,如果我要将它打印出来,它会留下一个空白行.
以下是我的两个具有相同问题的迭代.
def compose_line5(self, synset_offset, pointer_list):
self.line5 = ''''''
for item in pointer_list:
self.line5 += '''http://www.example.org/lexicon#'''+synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+pointer_list.next()+'''\n'''
break
return self.line5
def compose_line6(self, pointer_list, synset_list):
self.line6 = ''''''
for item in synset_list:
self.line6 += '''http://www.example.org/lexicon#'''+pointer_list.next()+''' http://www.monnetproject.eu/lemon#pos '''+synset_list.next()+'''\n'''
break
return self.line6
Run Code Online (Sandbox Code Playgroud)
这是我没有休息时得到的错误:
Traceback (most recent call last):
File "wordnet.py", line 225, in <module>
wordnet.line_for_loop(my_file)
File "wordnet.py", line 62, in line_for_loop
self.compose_line5(self.synset_offset, self.pointer_list)
File "wordnet.py", line 186, in compose_line5
self.line5 += '''http://www.example.org/lexicon#'''+self.synset_offset+''' http://www.monnetproject.eu/lemon#has_ptr '''+self.pointer_list.next()+'''\n'''
StopIteration
Run Code Online (Sandbox Code Playgroud)
有没有快速解决这个问题,或者我必须捕获我使用iter()的每个方法的异常?
我正在尝试遍历列表,我需要在迭代到达列表末尾时执行特定操作,请参阅下面的示例:
data = [1, 2, 3]
data_iter = data.__iter__()
try:
while True:
item = data_iter.next()
try:
do_stuff(item)
break # we just need to do stuff with the first successful item
except:
handle_errors(item) # in case of no success, handle and skip to next item
except StopIteration:
raise Exception("All items weren't successful")
Run Code Online (Sandbox Code Playgroud)
我相信这段代码不是Pythonic,所以我正在寻找更好的方法.我认为理想的代码应该看起来像下面的假设:
data = [1, 2, 3]
for item in data:
try:
do_stuff(item)
break # we just need to do stuff with the first successful item
except:
handle_errors(item) # in …Run Code Online (Sandbox Code Playgroud) 有人可以帮我理解PEP479是关于什么的吗?我正在阅读文档而无法理解它.
摘要说:
此PEP建议对生成器进行更改:当在生成器内引发StopIteration时,将其替换为RuntimeError.(更准确地说,当异常即将从生成器的堆栈帧中冒出时,就会发生这种情况.)
那么,例如,这样的循环是否仍然有效?
it = iter([1,2,3])
try:
i = next(it)
while True:
i = next(it)
except StopIteration:
pass
Run Code Online (Sandbox Code Playgroud)
或者它是否意味着如果我有这样的生成器定义:
def gen():
yield from range(5)
raise StopIteration
Run Code Online (Sandbox Code Playgroud)
在StopIteration将要被替换RuntimeError?
如果有人能够对此有所了解,我将非常感激.