python decompose a list

寵の児 提交于 2019-12-17 14:45:09

问题


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.


回答1:


If you want to pass a list of arguments to a function, you can use *, the splat operator. Here's how it works:

list = [1, 2, 3]
function_that_takes_3_arguments(*list)

If you want to assign the contents of a list to a variable, you can list unpacking:

a, b, c = list # a=1, b=2, c=3



回答2:


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.

li = [[1], [2], [3]]
a, b, c = tuple(li)
print a  # [1]



回答3:


The correct answer to the OP's question: "what is that operator" which transforms the list [[1],[2],[3]] to [1], [2], [3] is tuple() since [1], [2], [3] is a tuple. The builtin function tuple 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:

a, b, c = [[1],[2],[3]]

gives the same result as

a, b, c = tuple([[1],[2],[3]])

This may not be what the OP wanted but it is the correct answer to the question as asked.




回答4:


This can be achieved by running sum(list_name,[]) as mentioned here.

You may also find this question on flattening shallow lists relevant.



来源:https://stackoverflow.com/questions/6319612/python-decompose-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!