在Python中* zip(list1,list2)返回什么类型的对象?

问题描述:

可能重复:
Python: Once and for all. What does the Star operator mean in Python?在Python中* zip(list1,list2)返回什么类型的对象?

x = [1, 2, 3] 
y = [4, 5, 6] 
zipped = zip(x, y) 
list(zipped) 

x2, y2 = zip(*zip(x, y)) 
x == list(x2) and y == list(y2) 

什么类型的对象呢*zip(x, y)回报?为什么

res = *zip(x, y) 
print(res) 

不起作用?

+0

第二个示例不起作用,因为它不“返回对象”。 – 2012-03-17 22:58:58

Python中的星号“运算符”不返回对象;这是一个句法结构,意思是“用给出的列表作为参数来调用函数”。

所以:

X = [1,2,3]
F(* X)

相当于:

F(1,2,3)

关于这个(不是我的)的博客条目:http://www.technovelty.org/code/python/asterisk.html

+0

Python文档在此上下文中调用'*'作为操作符,但这有点误导;直觉上,操作符应该返回一个对象,但这实际上是一个语法结构。 – Christophe 2012-03-18 19:18:47

*运算符在Python中通常被称为scatter,它是用用于将元组或列表分散到多个变量中,因此通常用于输入参数。 http://en.wikibooks.org/wiki/Think_Python/Tuples

双星**在字典上做了相同的操作,对命名参数非常有用!

*zip(x, y)不返回一个类型,*用于unpack arguments一个函数,在你的情况下再次zip

With x = [1, 2, 3] and y = [4, 5, 6]zip(x, y)的结果是[(1, 4), (2, 5), (3, 6)]

这表示zip(*zip(x, y))zip((1, 4), (2, 5), (3, 6))相同,其结果为[(1, 2, 3), (4, 5, 6)]