简体   繁体   中英

Python - asterisk when zipping

I'm a newbie with python and I don't understand why doesn't the following work:

ea = zip([[200, 1], [10, 1]])

since I'm getting

[([200, 1],), ([10, 1],)]

while I should add an asterisk like

ea = zip(*[[200, 1], [10, 1]])

to obtain the result I want, ie

[(200, 10), (1, 1)]

I thought * was meant to convert the list to a tuple, what am I getting wrong?

If you have time you can read this post , it's good resource to understand how * works in Python.

The asterisk in Python unpacks arguments for a function call, please refer to here

z = [4, 5, 6]
f(*z)

will be same as:

f(4,5,6)

** in dictionary does similar work as * in list.

zip expects multiple arguments, like this:

>>> zip([200, 1], [10, 1])
[(200, 10), (1, 1)]

If you want to use only one argument, then use the * because it has the effect of breaking it up into multiple arguments:

>>> zip(*[[200, 1], [10, 1]])
[(200, 10), (1, 1)]
>>> 

The * does not convert lists to tuples. It unpacks lists ( documentation ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM