The meaning of data_dict={h:v for h,v in zip(header,zip(header,zip(*value)} in python data analysis

The prototype of the zip function is: zip([iterable, …])

The parameter iterable is an iterable object and can have multiple parameters. The function returns a list of tuples, where the ith tuple contains the ith element of each parameter sequence. The length of the returned list is truncated to the length of the shortest argument sequence. With only one sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

import numpy as np
a=[1,2,3,4,5]
b=(1,2,3,4,5)
c=np.arange(5)
d="zhang"
zz=zip(a,b,c,d)
print(zz)

输出:
[(1, 1, 0, 'z'), (2, 2, 1, 'h'), (3, 3, 2, 'a'), (4, 4, 3, 'n'), (5, 5, 4, 'g')]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

when there are no parameters

import numpy as np
zz=zip()
print(zz)

输出:[]
  • 1
  • 2
  • 3
  • 4
  • 5

when there is only one parameter

import numpy as np
a=[1,2,3]
zz=zip(a)
print(zz)

输出:[(1,), (2,), (3,)]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

When multiple parameters have different lengths

import numpy as np
a=[1,2,3]
b=[1,2,3,4]
c=[1,2,3,4,5]
zz=zip(a,b,c)
print(zz)

输出:[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

zip() combined with the * operator can be used to unzip a list, see the following code:

import numpy as np
a=[1,2,3]
b=[4,5,6]
c=[7,8,9]
zz=zip(a,b,c)
print(zz)

x,y,z=zip(*zz)
print(x)
print(y)
print(z)

输出:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Note that each output here is a tuple, not necessarily the original type, but the value does not change (unless the original parameter list length is different, see the code below)

import numpy as np
a=[1,2,3]
b=[4,5,6,7]
c=[8,9,10,11,12]
zz=zip(a,b,c)
print(zz)

x,y,z=zip(*zz)
print(x)
print(y)
print(z)

输出:
[(1, 4, 8), (2, 5, 9), (3, 6, 10)]
(1, 2, 3)
(4, 5, 6)
(8, 9, 10)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

The unzip list b and c have less values.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325162315&siteId=291194637