开发者

Left hand side of assignment with infinite generators

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_o开发者_开发问答f_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
"""


When you know the var_list's length, you could use itertools.islice to cut off the infinite generator:

>>> import itertools
>>> infgen = itertools.cycle([1,4,9])
>>> a,b,c,d = itertools.islice(infgen, 4)
>>> a,b,c,d
(1, 4, 9, 1)

It works for assignment to a slice of list too.

>>> lst = [0]*20
>>> lst[2:10:2] = itertools.islice(infgen, 4)
>>> lst
[0, 0, 4, 0, 9, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜