Please explain a python zip and unpacking solution [duplicate]

可紊 提交于 2019-12-06 10:35:38
Martijn Pieters

*expression applies argument unpacking to the function call. It takes the expression part, which has to resolve to a sequence, and makes each element in that sequence a separate parameter to the function.

So, zip(x, y) returns a sequence, and each element in that sequence is made an argument to the outer zip() function.

For zip(*[(i*10, i*12) for i in xrange(4)]) it is perhaps a little clearer; there are several elements here:

  • [(i*10, i*12) for i in xrange(4)] (should be range() in python 3) creates a list with 4 tuples, [(0, 0), (10, 12), (20, 24), (30, 36)]
  • The zip(*...) part then takes each of those 4 tuples and passes those as arguments to the zip() function.
  • zip() takes each tuple and pairs their elements; two elements per tuple means the result is 2 lists of 4 values each.

Because the zip() function return two sequences, they can be assigned to the two variables.

I would have found the following a far more readable version of the same expression:

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