In Python what type of object does *zip(list1, list2) return? [duplicate]

余生颓废 提交于 2019-12-13 17:59:49

问题


Possible Duplicate:
Python: Once and for all. What does the Star operator mean in Python?

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)

What type of object does *zip(x, y) return? Why

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

doesn't work?


回答1:


The asterisk "operator" in Python does not return an object; it's a syntactic construction meaning "call the function with the list given as arguments."

So:

x = [1, 2, 3]
f(*x)

is equivalent to:

f(1, 2, 3)

Blog entry on this (not mine): http://www.technovelty.org/code/python/asterisk.html




回答2:


*zip(x, y) does not return a type, the * is used to unpack arguments to a function, in your case again zip.

With x = [1, 2, 3] and y = [4, 5, 6] the result of zip(x, y) is [(1, 4), (2, 5), (3, 6)].

This means that zip(*zip(x, y)) is the same as zip((1, 4), (2, 5), (3, 6)) and the result of that becomes [(1, 2, 3), (4, 5, 6)].




回答3:


The * operator in python is commonly known as scatter, it is useful for scatter tuples or lists into a number of variables, and thus is commonly used for input arguments. http://en.wikibooks.org/wiki/Think_Python/Tuples

The double star ** does the same operation on a dictionary, and is very useful for named arguments!



来源:https://stackoverflow.com/questions/9754453/in-python-what-type-of-object-does-ziplist1-list2-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!