I am trying to make a function that does something similar to “zip”. My problem is that the part
JavaScript
x
2
1
a = L4[l:len(L4):len(L)]
2
doesn’t work. In the case below, it should take every third element from the L4, and append it to a new list, so I ended up with [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
, but that is not really what is happening. Also, it would be even better if I could make tuples, so it would look like [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
, but I don’t know how to do that…
JavaScript
1
16
16
1
L = [[1,2,3], [4,5,6], [7,8,9]]
2
L4 = []
3
def my_zip(L):
4
l = 0
5
for i in L:
6
if isinstance(i, list):
7
my_zip(i)
8
else:
9
L4.append(i)
10
while l < len(L):
11
a = L4[l:len(L4):len(L)]
12
l += 1
13
L5.append(a)
14
return L5
15
print(my_zip(L))
16
Advertisement
Answer
Try this one.
JavaScript
1
20
20
1
def zip_copy(*args):
2
lst = []
3
i = 0
4
t = tuple()
5
for a in range(len(min(args,key=len))):
6
for a in args:
7
t+=(a[i],)
8
i+=1
9
lst +=(t,)
10
t = tuple()
11
return lst
12
print(zip_copy([1,2],[3,4],[3,5])) # [(1, 3, 3), (2, 4, 5)]
13
print(list(zip([1,2],[3,4],[3,5]))) # [(1, 3, 3), (2, 4, 5)]
14
# ------------------------------------#
15
print(zip_copy([1,2])) # [(1,), (2,)]
16
print(list(zip([1,2]))) # [(1,), (2,)]
17
# ------------------------------------ #
18
print(zip_copy("Hello","Hii")) # [('H', 'H'), ('e', 'i'), ('l', 'i')]
19
print(list(zip("Hello","Hii"))) # [('H', 'H'), ('e', 'i'), ('l', 'i')]
20