如何生成预解包列表?

发布于 2024-09-16 13:15:09 字数 1058 浏览 11 评论 0原文

我有一个在 itertools.groupby 操作中创建的列表:

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

例如,如果 subset_of_grp 结果是 [1, 2, 3, 4][5, 6, 7, 8]:

for m in yield_unpacked_list():
    print m

将打印出:

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

现在,回到我的函数定义。显然,以下是语法错误(* 运算符):

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

我希望 same print 循环的以下结果不包含 [list] 括号:

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

请注意,print 此处仅用于说明目的。我还有其他函数可以从简化的元组结构中受益。

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:

('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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

莳間冲淡了誓言ζ 2024-09-23 13:15:09

yield(key,) + tuple(subset_of_grp)

yield (key,) + tuple(subset_of_grp)

一曲爱恨情仇 2024-09-23 13:15:09
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)

从您想要打印的结果来看,很明显您想要生成一个元组 - 不知道为什么您将其称为“解压列表”,但是,无论如何,您就在那里。我还删除了对 list 的几个调用,这些调用在您的代码中根本没有任何作用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文