具有无限生成器的赋值的左侧
抱歉重复我之前的问题,但我想询问可以解决问题的具体数据。我想要这个结果
tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator))
,因为这实际上是不可能的
a, b, c, d = (val for val in infite_generator)
,然后我想在单行中执行
for var in var_list:
var = next(infinite_generator)
是否有解释器挂钩来获取赋值左侧变量数量的元信息?更好的是,我可以自动执行最后一段代码(包括左侧是带有变量索引和步骤的切片的情况)
还有什么方法可以生成变量的生成器,该变量将位于赋值的左侧。
编辑:这不会在Python3中停止:
def incr(a):
while True:
yield a
a += 1
a = [None for i in range(20)]
a[3:3:3], *_ = incr(1)
print(a)
与以下相同:
a,b,c,d, *_ = incr(1)
print(a, b, c, d)
即使它没有切片(实际上索引将是变量,这只是测试)。我知道 islice 等,但它太慢了。
这也会产生错误:
a = 1000*[True]
bound = int(len(a) ** 0.5)
for i in range(3, bound, 2):
a[3::i], *x = [[False] for _ in range(bound)]
""" Error:
ValueError: attempt to assign sequence of size 1 to extended slice of size 333
"""
并且这个:
a = 1000*[True]
bound = int(len(a) ** 0.5)
for i in range(3, bound, 2):
a[3::i], *x = [False] * bound
""" Error:
TypeError: must assign iterable to extended slice
"""
Sorry to double my earlier question, but I thought to ask specific data which would solve the problem. I want this result
tuple_of_vars = (item for _, item for zip(tuple_of_vars, new_vals_generator))
as this is not possible
a, b, c, d = (val for val in infite_generator)
actually then I want to do in single line
for var in var_list:
var = next(infinite_generator)
Is there any interpreter hook to take metainformation of number of vars at left hand side of assignement? Better would be though that I could just do automatically this last bit of code (including cases with left side which is slice with variable indexes and step)
Also is there way to make generator of variables which would be left hands side of assignment.
EDIT: This does not stop in Python3:
def incr(a):
while True:
yield a
a += 1
a = [None for i in range(20)]
a[3:3:3], *_ = incr(1)
print(a)
Same with:
a,b,c,d, *_ = incr(1)
print(a, b, c, d)
Even it has not slice (actually the indexes would be variables, this is only test). I am aware of islice etc but it is too slow.
This produce also error:
a = 1000*[True]
bound = int(len(a) ** 0.5)
for i in range(3, bound, 2):
a[3::i], *x = [[False] for _ in range(bound)]
""" Error:
ValueError: attempt to assign sequence of size 1 to extended slice of size 333
"""
And this:
a = 1000*[True]
bound = int(len(a) ** 0.5)
for i in range(3, bound, 2):
a[3::i], *x = [False] * bound
""" Error:
TypeError: must assign iterable to extended slice
"""
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您知道
var_list
的长度时,您可以使用itertools.islice
切断无限生成器:它也适用于分配给列表的切片。
When you know the
var_list
's length, you could useitertools.islice
to cut off the infinite generator:It works for assignment to a slice of list too.