Displaying certain vectors in a 2D Python list

3

I have the following situation: - I have a variable called (distrow_vector). This variable receives a 2D list with multiple vectors. - I want it to be displayed, only vectors whose sum of their indexes are less than 100. - I have the code below, but it is not doing what I need.

def funcao_fitness():
    fitness = 0
    i = 0
    vetor_distancias = [[10,20,30,40],[50,60,70,80],[5,6,7,8],[100,200,300,400],[9,15,25,30]]
    for i in vetor_distancias:
        fitness = (fitness + i) if i <= 100
        print (fitness[i])
    return fitness
print (funcao_fitness())

Thanks in advance for your help.

    
asked by anonymous 26.02.2017 / 19:43

2 answers

2

You can do this:

def funcao_fitness():
    fitness = []
    vetor_distancias = [[10,20,30,40],[50,60,70,80],[5,6,7,8],[100,200,300,400],[9,15,25,30]]
    for subl in vetor_distancias:
        if sum(subl) <= 100:
            fitness.append(subl)
    return fitness
print funcao_fitness()

Or with list compreension :

def funcao_fitness():
    vetor_distancias = [[10,20,30,40],[50,60,70,80],[5,6,7,8],[100,200,300,400],[9,15,25,30]]
    return [subl for subl in vetor_distancias if sum(subl) <= 100]
print funcao_fitness()

The function will return a list with all sublists whose sum of their values is < = 100

    
26.02.2017 / 20:09
1

Good as I was trying to solve also for study, I decided to post post ...

array = [[10,20,30,40],[50,60,70,80],[5,6,7,8],[100,200,300,400],[9,15,25,30]]
result = [i for i in array if sum(i) < 100]
print(result)

The only difference from (@Miguel's answer) will be the same result ..

Where the returned solution will be:

[[10, 20, 30, 40], [5, 6, 7, 8], [9, 15, 25, 30]]

And the correct one would be:

[[5, 6, 7, 8], [9, 15, 25, 30]]

But it may be an error in interpretation ... Due to the operator <= where by the statement the correct is < ...

See the Ideone

    
26.02.2017 / 20:57