Question

Problem with IF in Python

  • 19 August 2016
  • 2 replies
  • 2 views

Userlevel 4
Badge +30

Hello FME User`s,

I have a problem with my Script python. I have two values attribute tamanho: 256,757. I break this inside Python script and generate a list values.

I need to generate two attributes for theses attributes tamanho: inicial{} and final {}.

For the firts register is OK: inicial{0} and final{0}

But when execute inside this script to second register is wrong.

The results right it will be to second register:

inicial{1} = final{0} + 1

final{1} = inicial{1} + attribute lenght this list ( int(listaTamanhoTrecho[controle] ))

Attached my template.


2 replies

Userlevel 2
Badge +17

Hi @danilo_inovacao, program doesn't work as expected,
it just works according to the source you wrote ;-) Maybe this script generates your desired result.

from operator import itemgetter

def processFeature(feature):
    tamanhoTrecho = str(feature.getAttribute('tamanho'))
    ordem = str(feature.getAttribute('ordem'))
    ppPai = int(feature.getAttribute('tam_inicial_pai'))
    
    listaTamanhoTrecho = [int(s) for s in tamanhoTrecho.split(',')]
    listaOrdem = [int(s) for s in ordem.split(',')]

    # zip the two lists and sort it by the first element (i.e. 'ordem')    
    data = sorted(zip(listaOrdem, listaTamanhoTrecho), key=itemgetter(0))

    inicial = [ppPai + 1]
    final = [ppPai + data[0][1]]
    for _, t in data[1:]:
        ini = final[-1] + 1
        inicial.append(ini)
        final.append(ini + t)

    for i, (ini, fin) in enumerate(zip(inicial, final)):
        feature.setAttribute('inicial{%d}' % i, ini)
        feature.setAttribute('final{%d}' % i, fin)

Userlevel 4
Badge +30

Hi @danilo_inovacao, program doesn't work as expected,
it just works according to the source you wrote ;-) Maybe this script generates your desired result.

from operator import itemgetter

def processFeature(feature):
    tamanhoTrecho = str(feature.getAttribute('tamanho'))
    ordem = str(feature.getAttribute('ordem'))
    ppPai = int(feature.getAttribute('tam_inicial_pai'))
    
    listaTamanhoTrecho = [int(s) for s in tamanhoTrecho.split(',')]
    listaOrdem = [int(s) for s in ordem.split(',')]

    # zip the two lists and sort it by the first element (i.e. 'ordem')    
    data = sorted(zip(listaOrdem, listaTamanhoTrecho), key=itemgetter(0))

    inicial = [ppPai + 1]
    final = [ppPai + data[0][1]]
    for _, t in data[1:]:
        ini = final[-1] + 1
        inicial.append(ini)
        final.append(ini + t)

    for i, (ini, fin) in enumerate(zip(inicial, final)):
        feature.setAttribute('inicial{%d}' % i, ini)
        feature.setAttribute('final{%d}' % i, fin)

Amazing @takashi Your script was helpful for me.

 

Thanks !!!

 

Reply