user3526630 user3526630 - 3 months ago 18
Python Question

Add value into tuple (zip() inside for loop ) in Python

I need to format a list of list into a list of tuples, the desired outcome is:

>>A = [[1, 2, 3]]
>>A.append([1, 2, 3])
>>A.append([1, 2, 3])
>>print A
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]


And my desired output is:

>>zip (A[0],A[1],A[2])
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]


Now imagine that the list A is very large and I cannot do that process writing a small line of code, if I try to loop the zip() function the outcome is as follows:

>>print zip (A[0],a)
>>[(1, (1, 1, 1)), (2, (2, 2, 2)), (3, (3, 3, 3))]


The nasty solution that I came up was using a recursive loop:

>>B = zip(A[0])
>>for idx,val in enumerate(A):
for idx1,val1 in enumerate(B):
B[idx1] = val1 + (A[idx][idx1],)


That returns the desired result:

[(1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3)]


Hence, is there a proper/cleaner/faster way to solve this problem?

(Because it is an embedded package of Python I cannot use Pandas nut NumPy is allowed in an early version)

Answer

try zip(*A), which is exactly zip(A[0],A[1],...)

(that's true for any function, not just zip). https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

Comments