Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
有没有办法把这个生成器函数转换成一个相对简单的生成器理解?(以下对我有用,我只是想了解可能的选项是什么)
def annotate(x): n = 0 for item in x: yield(item,n) n = n + 1
使用示例:
>>> for line in annotate([3,4,5]): ... print line ... (3, 0) (4, 1) (5, 2)
您可以使用enumerate:
enumerate
comp = ((y,x) for x,y in enumerate(iterable))
示范:
>>> annotated = ((y,x) for x,y in enumerate(range(1,4))) >>> for line in annotated: print line ... (1, 0) (2, 1) (3, 2)
虽然,通常你只会enumerate以相反的顺序使用和解包。:^)