在python中有没有等效的PHP list()函数?例如:
PHP:
list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";
答案 0 :(得分:28)
>>> 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