Python中的PHP list()等效

Dre*_*rew 14 php python

在python中有没有等效的PHP list()函数?例如:

PHP:

list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";
Run Code Online (Sandbox Code Playgroud)

dhg*_*dhg 30

>>> a, b, c = [1, 2, 3]
>>> print a, b, c
1 2 3
Run Code Online (Sandbox Code Playgroud)

或直接翻译您的案例:

>>> myIndexArray = [1, 2, 3]
>>> first, second, third = myIndexArray
>>> print "First: %d, Second: %d" % (first, second)
First: 1, Second: 2
Run Code Online (Sandbox Code Playgroud)

Python通过调用__iter__右侧表达式上的方法并将每个项目分配给左侧的变量来实现此功能.这使您可以定义如何将自定义对象解压缩到多变量赋值中:

>>> class MyClass(object):
...   def __iter__(self):
...     return iter([1, 2, 3])
... 
>>> a, b, c = MyClass()
>>> print a, b, c
1 2 3
Run Code Online (Sandbox Code Playgroud)