开发者

How do I yield a pre-unpacked list?

开发者 https://www.devze.com 2023-01-13 06:54 出处:网络
I have a list that is created within an itertools.groupby operation: def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):

I have a list that is created within an itertools.groupby operation:

def yield_unpacked_list():
    for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
        subset_of_grp = list(item[2] for item in list(grp))
        yield key, subset_of_grp

If, for example, subset_of_grp turns out to be [1, 2, 3, 4] and [5, 6, 7, 8]:

for m in yield_unpacked_list():
    print m

would print out:

('first_key', [1, 2, 3, 4])
('second_key', [5, 6, 7, 8])

Now, going back to my function definition. Obviously the following is a syntax error (the * operator):

def yield_unpacked_list():
    for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
        subset_of_grp = list(item[2] for item in list(grp))
        yield key, *subset_of_grp

I want the following result for the same print loop to be without the [list] brackets:

开发者_C百科
('first_key', 1, 2, 3, 4)
('second_key', 5, 6, 7, 8)

Note that print is only for illustrative purposes here. I have other functions that would benefit from the simplified tuple structure.


yield (key,) + tuple(subset_of_grp)


def yield_unpacked_list():
    for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
        yield (key,) + tuple(item[2] for item in grp)

From the result you want for printing, it's clear that you want to yield a tuple -- no idea why you call it an "unpacked list" instead, but, anyway, there you are. I also removed a couple of calls to list that simply served no useful role at all in your code.

0

精彩评论

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

关注公众号