Combine all x, y, z coordinates of a list of tuples

6

I have the following list with several points:

[(14, 9, 7), (11, 1, 20), (1, 1, 7), (13, 9, 1), (9, 13, 4), (20, 1, 4), (17, 6, 8), (14, 10, 1), (14, 2, 17), (7, 20, 7)]

Each element of the list is a tuple with the coordinates (x, y, z), what I need is to join all x, y and z to look like this:

[(x,x,x,x,x...), (y,y,y,y,y,y...), (z,z,z,z,z,z...)]

I've tried this but it did not work:

lista = []
for i in coords:
    lista.append(i[0])
    lista.append(i[1])
    lista.append(i[2])

But it did not turn out to be all mixed together

    
asked by anonymous 06.01.2017 / 15:14

1 answer

7

You can do this by using zip () :

coords = [(14, 9, 7), (11, 1, 20), (1, 1, 7), (13, 9, 1), (9, 13, 4), (20, 1, 4), (17, 6, 8), (14, 10, 1), (14, 2, 17), (7, 20, 7)]

combin = zip(*coords) # aqui fazes unpacking de cada tuple e esta funcao vai juntar todos os indices 0, 1, 2 dos tuples em uma lista separada
print(list(combin))

Output:

  

[(14, 11, 1, 13, 9, 20, 17, 14, 14, 7), (9,1,1,9,13,1,6,10,2,20) , 20, 7, 1, 4, 4, 8, 1, 17, 7)]

DEMONSTRATION

To do the way you were trying is also possible, you were to make confusion with the operation inside the cycle, you must create 3 different lists that will store the x's, y's, and z's respectively:

lista = [[],[],[]] # [[x,x,x..], [y,y,y..], [z,z,z..]]
for x, y, z in coords: # fazer o unpacking de cada tuple
    lista[0].append(x)
    lista[1].append(y)
    lista[2].append(z)
print(lista)

Output:

  

[[14, 11, 1, 13, 9, 20, 17, 14, 14, 7], [9,1,1,9,13,1,6,10,2,20] , 20, 7, 1, 4, 4, 8, 1, 17, 7]]

DEMONSTRATION

If you need every internal list to be even a tuple, after performing the for operation, just do:

lista = [tuple(i) for i in lista]

But note that the first one is more correct / pythonic, the latter is to realize that it also gives and what logic to adopt for it.

    
06.01.2017 / 15:16