Difference between zip(list) and zip(*list)

This question already has an answer here:

  • What does the Star operator mean? [duplicate] 5 answers

  • zip wants a bunch of arguments to zip together, but what you have is a single argument (a list, whose elements are also lists). The * in a function call "unpacks" a list (or other iterable), making each of its elements a separate argument. So without the * , you're doing zip( [[1,2,3],[4,5,6]] ) . With the * , you're doing zip([1,2,3], [4,5,6]) .


    The * operator unpacks arguments in a function invocation statement.

    Consider this

    def add(x, y):
       return x + y
    

    if you have a list t = [1,2] , you can either say add(t[0], t[1]) which is needlessly verbose or you can "unpack" t into separate arguments using the * operator like so add(*t) .

    This is what's going on in your example. zip(p) is like running zip([[1,2,3],[4,5,6]]) . Zip has a single argument here so it trivially just returns it as a tuple.

    zip(*p) is like running zip([1,2,3], [4,5,6]) . This is similar to running zip(p[0], p[1]) and you get the expected output.


    While this isn't the answer the question you asked, it should help. Since zip is used to combine two lists, you should do something like this list(zip(p[0], p[1])) to accomplish what you'd expect.

    链接地址: http://www.djcxy.com/p/53636.html

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

    下一篇: zip(list)和zip(* list)之间的区别