python 分解列表
我记得我曾经见过一个能够在Python中分解列表的运算符。
例如,
[[1],[2],[3]]
通过应用该运算符,您会得到
[1], [2], [3]
该运算符是什么,任何帮助将不胜感激。
I remember I once seen a operator which is able to decompose a list in python.
for example
[[1],[2],[3]]
by applying that operator, you get
[1], [2], [3]
what is that operator, any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果要将参数列表传递给函数,可以使用 splat 运算符
*
。它的工作原理如下:如果要将列表的内容分配给变量,可以对列表进行解包:
If you want to pass a list of arguments to a function, you can use
*
, the splat operator. Here's how it works:If you want to assign the contents of a list to a variable, you can list unpacking:
您可以使用
tuple
函数将列表转换为元组。具有三个元素的元组实际上与三个单独的元素没有任何不同,但它提供了一种将所有三个元素一起使用的便捷方法。You can use the
tuple
function to convert a list to a tuple. A tuple with three elements isn't really any different from three separate elements, but it gives a handy way to work with all three together.OP问题的正确答案:“那个运算符是什么”,它将列表
[[1],[2],[3]]
转换为[1], [2], [3]
是tuple()
因为[1], [2], [3]
是一个元组。内置函数 tuple 会将任何序列或可迭代对象转换为元组,尽管很少需要这样做,因为正如已经指出的,解包列表与解包元组一样简单:给出结果与
这可能不是OP想要的,但它是所问问题的正确答案。
The correct answer to the OP's question: "what is that operator" which transforms the list
[[1],[2],[3]]
to[1], [2], [3]
istuple()
since[1], [2], [3]
is a tuple. The builtin functiontuple
will convert any sequence or iterable to a tuple, although there is seldom a need to do so since, as already pointed out, unpacking a list is as easy as unpacking a tuple:gives the same result as
This may not be what the OP wanted but it is the correct answer to the question as asked.
这可以通过运行
sum(list_name,[])
来实现,如上所述 此处。您可能还会发现此问题与展平浅列表相关。
This can be achieved by running
sum(list_name,[])
as mentioned here.You may also find this question on flattening shallow lists relevant.