如何生成预解包列表?
我有一个在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
yield(key,) + tuple(subset_of_grp)
yield (key,) + tuple(subset_of_grp)
从您想要打印的结果来看,很明显您想要生成一个元组 - 不知道为什么您将其称为“解压列表”,但是,无论如何,您就在那里。我还删除了对
list
的几个调用,这些调用在您的代码中根本没有任何作用。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 tolist
that simply served no useful role at all in your code.