函数调用中的星号 [英] Asterisk in function call

查看:92
本文介绍了函数调用中的星号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用itertools.chain以这种方式拉平"列表列表:

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))

推荐答案

*是"splat"运算符:它将一个列表作为输入,并将其扩展为函数调用中的实际位置参数.

* is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call.

因此,如果uniqueCrossTabs[ [ 1, 2 ], [ 3, 4 ] ],则itertools.chain(*uniqueCrossTabs)与说itertools.chain([ 1, 2 ], [ 3, 4 ])

So if uniqueCrossTabs was [ [ 1, 2 ], [ 3, 4 ] ], then itertools.chain(*uniqueCrossTabs) is the same as saying itertools.chain([ 1, 2 ], [ 3, 4 ])

这显然与仅传递uniqueCrossTabs有所不同.对于您的情况,您有一个要拼合的列表清单. itertools.chain()的作用是在传递给它的所有位置参数的串联上返回一个迭代器,其中每个位置参数本身都是可迭代的.

This is obviously different from passing in just uniqueCrossTabs. In your case, you have a list of lists that you wish to flatten; what itertools.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.

换句话说,您想将uniqueCrossTabs中的每个列表作为chain()的参数传递,这会将它们链接在一起,但是您没有将列表包含在单独的变量中,因此可以使用*操作符,以将列表列表扩展为几个列表参数.

In other words, you want to pass each list in uniqueCrossTabs as an argument to chain(), 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.

正如Jochen Ritzel在评论中指出的, chain.from_iterable() 更好-适用于此操作,因为它假定一个可迭代对象开始于一个可迭代对象.然后,您的代码将变得简单:

As Jochen Ritzel has pointed out in the comments, 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:

uniqueCrossTabs = list(itertools.chain.from_iterable(uniqueCrossTabs))

这篇关于函数调用中的星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆