[英]Is there a way to init a list without using square bracket in 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
也可以。
僅適用於python 2.x :
>>> def list_cons(*args):
return map(None,args)
>>> list_cons(1,2,3,4)
[1, 2, 3, 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.