Match all coordinates x, y, z from a list of tuples

Asked

Viewed 478 times

8

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 that but it didn’t work:

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

But it didn’t work getting all mixed up

1 answer

8


You can do it 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), (7, 20, 7, 1, 4, 4, 8, 1, 17, 7)]

DEMONSTRATION

To do it the way you were trying to do it is possible, you were just messing with the operation within 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], [7, 20, 7, 1, 4, 4, 8, 1, 17, 7]]

DEMONSTRATION

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

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

But note that the first one is more correct/pythonica, the last one is to realize that it also gives and the logic to adopt for this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.