PHP列表()在Python中等效


PHP list() equivalent in Python

python中有类似于PHP list()函数的函数吗?例如:

PHP:

list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";
>>> a, b, c = [1, 2, 3]
>>> print a, b, c
1 2 3

或者直接翻译您的案例:

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

Python通过调用右侧表达式上的__iter__方法并将每个项分配给左侧的变量来实现此功能。这允许您定义如何将自定义对象解包为多变量赋值:

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