python 分解列表

发布于 2024-11-15 04:20:57 字数 177 浏览 0 评论 0原文

我记得我曾经见过一个能够在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

内心激荡 2024-11-22 04:20:57

如果要将参数列表传递给函数,可以使用 splat 运算符 *。它的工作原理如下:

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

如果要将列表的内容分配给变量,可以对列表进行解包:

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

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
薔薇婲 2024-11-22 04:20:57

您可以使用tuple函数将列表转换为元组。具有三个元素的元组实际上与三个单独的元素没有任何不同,但它提供了一种将所有三个元素一起使用的便捷方法。

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

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]
人间☆小暴躁 2024-11-22 04:20:57

OP问题的正确答案:“那个运算符是什么”,它将列表 [[1],[2],[3]] 转换为 [1], [2], [3]tuple() 因为 [1], [2], [3] 是一个元组。内置函数 tuple 会将任何序列或可迭代对象转换为元组,尽管很少需要这样做,因为正如已经指出的,解包列表与解包元组一样简单:

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

给出结果与

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

这可能不是OP想要的,但它是所问问题的正确答案。

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.

遗弃M 2024-11-22 04:20:57

这可以通过运行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文