函数调用中的星号
我正在使用 itertools.chain 以这种方式“展平”列表列表:
uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs))
这与说有什么不同:
uniqueCrossTabs = list(itertools.chain(uniqueCrossTabs))
I'm using itertools.chain to "flatten" a list of lists in this fashion:
uniqueCrossTabs = list(itertools.chain(*uniqueCrossTabs))
how is this different than saying:
uniqueCrossTabs = list(itertools.chain(uniqueCrossTabs))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
*
是“splat”运算符:它将像列表一样的可迭代对象作为输入,并将其扩展为函数调用中的实际位置参数。因此,如果
uniqueCrossTabs
为[[1, 2], [3, 4]]
,则itertools.chain(*uniqueCrossTabs)
是相同的正如所说的itertools.chain([1, 2], [3, 4])
这显然与仅传入
uniqueCrossTabs
不同。就您而言,您有一个想要展平的列表列表; itertools.chain() 的作用是在传递给它的所有位置参数的串联上返回一个迭代器,其中每个位置参数本身都是可迭代的。换句话说,您希望将
uniqueCrossTabs
中的每个列表作为参数传递给chain()
,这会将它们链接在一起,但您没有单独的列表变量,因此您可以使用*
运算符将列表列表展开为多个列表参数。chain.from_iterable()
是更适合此操作,因为它一开始就假设有一个可迭代的可迭代。然后你的代码就变得简单了:*
is the "splat" operator: It takes an iterable like a list as input, and expands it into actual positional arguments in the function call.So if
uniqueCrossTabs
were[[1, 2], [3, 4]]
, thenitertools.chain(*uniqueCrossTabs)
is the same as sayingitertools.chain([1, 2], [3, 4])
This is obviously different from passing in just
uniqueCrossTabs
. In your case, you have a list of lists that you wish to flatten; whatitertools.chain()
does is return an iterator over the concatenation of all the positional arguments you pass to it, where each positional argument is iterable in its own right.In other words, you want to pass each list in
uniqueCrossTabs
as an argument tochain()
, which will chain them together, but you don't have the lists in separate variables, so you use the*
operator to expand the list of lists into several list arguments.chain.from_iterable()
is better-suited for this operation, as it assumes a single iterable of iterables to begin with. Your code then becomes simply:它将序列拆分为函数调用的单独参数。
It splits the sequence into separate arguments for the function call.
只是解释概念/使用它的另一种方式。
Just an alternative way of explaining the concept/using it.