有没有办法在不使用Python中的方括号的情况下初始化列表?

有没有办法在不使用Python中的方括号的情况下初始化列表?

例如,是否有像list_cons这样的函数:

x = list_cons(1, 2, 3, 4)

相当于:

x = [1, 2, 3, 4]

In [1]: def list_cons(*args):
   ...:     return list(args)
   ...: 

In [2]: list_cons(1,2,3,4)
Out[2]: [1, 2, 3, 4]

使用列表构造函数并将它传递给一个元组。

x = list((1,2,3,4))

我认为这不是一个特别有用的功能。 输入括号如此困难? 也许我们可以给你一个更有用的答案,如果你解释你为什么要这样做。

不过,你可以在Python 3中做一件有趣的事情:

>>> (*x,) = 1, 2, 3, 4, 5
>>> x
[1, 2, 3, 4, 5]

你甚至可以省略括号 - *x, = 1, 2, 3, 4, 5也可以。

链接地址: http://www.djcxy.com/p/53555.html

上一篇: Is there a way to init a list without using square bracket in Python?

下一篇: Python 3: starred expression to unpack a list