gpt4 book ai didi

Python:理解(None for g in g if (yield from g) and False)

转载 作者:IT老高 更新时间:2023-10-28 20:48:39 29 4
gpt4 key购买 nike

James Powell 在他对即将举行的演示文稿的简短描述中说,他自豪地发明了最粗糙的 Python 单行代码之一:

(None for g in g if (yield from g) and False)

我正在尝试找出这个生成器,因为我使用的是 Python 2.7.x,所以我也遇到了 (yield from g) 表达式。

我该如何阅读,python 2.7.x 模拟是什么?


下面的讨论真棒!我想检查一下我的主要内容是否正确。

>>> l = [10, 11, iter(xrange(5)), 12, 13]
>>> g = iter(l)
>>> flat_g = (None for g in g if (yield from g) and False)
>>> list(flat_g)
[10, 11, 0, 1, 2, 3, 4, 12, 13]

这样说对吗?

最佳答案

这个表达式似乎是一种代码高尔夫的写法:

(a for b in g for a in b)

((或者可能是利用生成器委托(delegate)的动机,但恕我直言,可读性确实受到影响。))

例如:

#! /usr/bin/python3.3

g = ['abc', 'def', 'ghi']

a = (None for g in g if (yield from g) and False)
for x in a: print (x)

b = (a for b in g for a in b)
for x in b: print (x)

打印平展列表的两倍。

我认为如果你使用不同的变量名,它会变得更清晰:

(None for sublist in g if (yield from sublist) and False)

相同
(42 for sublist in g if (yield from sublist) and False)

由于 something 和 False,外部生成器不会产生任何东西,而内部生成器会产生所有子列表(子生成器、子可迭代对象)的所有元素。

也许这可以说明它是如何工作的:

('Sublist {}'.format(idx) for idx, sublist in enumerate(g) if (yield from sublist) or True)

显然原来的生成器可以简化成这样,省略最后的和False:

(None for sublist in g if (yield from sublist) )

修订:

感谢 Martijn Pieters 与我的固执斗争,我设法看到 (None for sublist in g if (yield from sublist) and False)(None for sublist in g if ( yield from sublist) ) 不等价。这里有一个 g 的例子,它会有所作为:

def f():
yield 1
return 2

def g():
yield f()

a = (None for sublist in g() if (yield from sublist) )
for x in a: print(x)
a = (None for sublist in g() if (yield from sublist) and False)
for x in a: print(x)

打印出来:

1
None
1

关于Python:理解(None for g in g if (yield from g) and False),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22254986/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com