Search code examples
pythonenumerate

Python: Enumeration based on an enumerated list


I have several vertexes that compose two triangles.

Vertexes:

A = [0.,0.,0.]
B = [2.,4.,0.]
C = [2.,3.,0.]
D = [1.,1.,0.]
vertex_list=[[0.,0.,0.],[2.,4.,0.],[2.,3.,0.],[1.,1.,0.]]

Triangles:

ABC=[[0.,0.,0.],[2.,4.,0.],[2.,3.,0.]]
ACD=[[0.,0.,0.],[2.,3.,0.],[1.,1.,0.]]

Now I need to export this data to a .txt file, to have the following output composed by two different parts:

1 0.0 0.0 0.0
2 2.0 4.0 0.0
3 2.0 3.0 0.0
4 1.0 1.0 0.0
end part 1
1 1 2 3
2 1 3 4
end part 2

The first part was easy, as I only needed to enumerate each vertex based on the aforementioned list.

file=open("test.dat","w")    
for i,list in enumerate(vertex_list,start=1):
        file.write("{} {} {} {}\n".format(i,list[0],list[1],list[2]))
file.close()

The problem is with the second part, as I need to enumerate each triangle (first column) and then assign the values previously given in part 1 to each vertex that compose the triangle.

e.g. triangle ABC is composed by vertexes 1, 2 and 3; triangle ACD is composed by vertexes 1,3 and 4, so the output (previously presented) should be:

1 1 2 3
2 1 3 4

I would appreciate any help you could give me on this. Thanks so much.


Solution

  • It looks like you would do something very similar.

    This would get the vertices:

    vertex_list=[[0.,0.,0.],[2.,4.,0.],[2.,3.,0.],[1.,1.,0.]]
    
    ABC=[[0.,0.,0.],[2.,4.,0.],[2.,3.,0.]]
    ACD=[[0.,0.,0.],[2.,3.,0.],[1.,1.,0.]]
    
    print('solve ABC')
    for i in ABC:
        for j,k in enumerate(vertex_list, start=1):
            if i==k:
                print('vertex found at', j)
    
    print('solve ACD')
    for i in ACD:
        for j,k in enumerate(vertex_list, start=1):
            if i==k:
                print('vertex found at', j)
    

    This is the output:

    solve ABC
    vertex found at 1
    vertex found at 2
    vertex found at 3
    solve ACD
    vertex found at 1
    vertex found at 3
    vertex found at 4
    

    or more generally make a list of triagles and solve in the same way like this:

    vertex_list=[[0.,0.,0.],[2.,4.,0.],[2.,3.,0.],[1.,1.,0.]]
    
    ABC=[[0.,0.,0.],[2.,4.,0.],[2.,3.,0.]]
    ACD=[[0.,0.,0.],[2.,3.,0.],[1.,1.,0.]]
    
    triamgles_list = [ABC, ACD]
    
    for c, t in enumerate(triamgles_list):
        print('solve item', c)
        for i in t:
            for j,k in enumerate(vertex_list, start=1):
                if i==k:
                    print('vertex found at', j)
    

    which gives this:

    solve item 0
    vertex found at 1
    vertex found at 2
    vertex found at 3
    solve item 1
    vertex found at 1
    vertex found at 3
    vertex found at 4