有人能向我解释一下打印函数对StopIteration错误造成的什么区别吗?我听说这与发电机内部设备有关,但我仍然不知道打印结果会如何工作。
import simhash
import re
jabb = ''' Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. "Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!" He took his vorpal sword in hand: Long time the manxome foe he sought -- So rested he by the Tumtum tree, And stood awhile in thought. And, as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came! One, two! One, two! And through and through The vorpal blade went snicker-snack! He left it dead, and with its head He went galumphing back. "And, has thou slain the Jabberwock? Come to my arms, my beamish boy! O frabjous day! Callooh! Callay!' He chortled in his joy. `Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe.'''
pope = '''There once was a man named 'Pope' Who loved an oscilloscope And the cyclical trace Of their carnal embrace Had a damned-near infinite slope!'''
tokej = re.split(r'\W+',
jabb.lower(),
flags=re.UNICODE)
tokep = re.split(r'\W+', pope.lower(), flags=re.UNICODE)
#this one works
shinji=[print(shingle) for shingle in simhash.shingle(''.join(tokej), 4)]
#but this one doesn't
shinji=[shingle for shingle in simhash.shingle(''.join(tokej), 4)]输出
...dadada...
['g', 'r', 'a', 'b']
['r', 'a', 'b', 'e']
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/simhash/__init__.py in shingle(tokens, window)
17 while True:
---> 18 yield [next(it) for it in its]
2 frames
StopIteration:
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
<ipython-input-23-1ccd829c7f86> in <listcomp>(.0)
5 tokej = re.split(r'\W+', jabb.lower(), flags=re.UNICODE)
6 tokep = re.split(r'\W+', pope.lower(), flags=re.UNICODE)
----> 7 shinji=[print(shingle) for shingle in simhash.shingle(''.join(tokej), 4)]
8 shinji=[shingle for shingle in simhash.shingle(''.join(tokej), 4)]
RuntimeError: generator raised StopIteration发布于 2022-05-19 00:23:07
好的,结果是停止迭代错误会在迭代器的末尾抛出,但是由于我使用的是打印函数,输出就像在后面发生了错误一样,因为它已经完成了所有的打印操作。因此,一些较旧的python代码抛出错误来停止生成器。哪个较新的蟒蛇不喜欢,所以他们停止了所有的‘那’。
https://stackoverflow.com/questions/72297161
复制相似问题