Python中的PHP list()等效函数

16

在Python中是否有与PHP list()函数相等的功能?例如:

PHP:

list($first, $second, $third) = $myIndexArray;
echo "First: $first, Second: $second";
1个回答

32
>>> 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

很好,这比我所需要的信息要多得多,这太棒了! - Drew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接