TypeError: 'float' object is not iterable in CHOICE function in 2D Python List

0

I have the code below and I can not get it to work. For, I need a vector from my 2D list to be chosen randomly with the CHOICE function and sum the values that are less than 85.0 and subtract the values when it is larger. However, the following error occurs:

  

"TypeError: 'float' object is not iterable".

def escolher():
    from random import choice
    a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
    fitness_1_temp = 0
    for i in a:
        for j in i:
            if j <= 85.0:
                fitness_1_temp += j
            else:
                fitness_1_temp -= j
    return fitness_1_temp

print (escolher())

Where am I going wrong?

Thanks in advance for the help.

    
asked by anonymous 24.02.2017 / 12:34

1 answer

1
from random import choice

def escolher():
    a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
    fitness_1_temp = 0
    for i in a:
        for j in i:
#---------------^^^
            if j <= 85.0:
                fitness_1_temp += j
            else:
                fitness_1_temp -= j
    return fitness_1_temp

print (escolher())

See in the code above, the part highlighted by the comment. You are trying to iterate over a value of type float . In fact, it does not make much sense to make the two loop , only one is able to solve the sum.

Let's say choice returned the first list:

a = [10.00,90.00,30.00,40.00]

By iterating for i in a , i will have the values 10.0, 90.0, 30.0 and 40.0, depending on the current iteration. From this value, you can do the following:

fitness_1_temp = (fitness_1_temp+i) if i <= 85.0 else (fitness_1_temp-i)
  

For the given examples, -10.0 will be returned when the first list is considered or 100.0 when the second.

See working at Repl.it at Ideone , and in the GitHub Gist .

Workaround

When we want to reduce a list to a single value, we can use the reduce operation. In Python 2, reduce is a built-in function , whereas in Python 3 it was built into the functools module. Both have the same format:

reduce(function, iterable[, initializer])

In Python 2:

from random import choice

def escolher():
    a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
    fitness_1_temp = reduce(lambda x, y: (x+y) if y <= 85.0 else (x-y), a, 0)
    return fitness_1_temp

print (escolher())

In Python 3:

from random import choice
from functools import reduce

def escolher():
    a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
    fitness_1_temp = reduce(lambda x, y: (x+y) if y <= 85.0 else (x-y), a, 0)
    return fitness_1_temp

print (escolher())

Same solution, you only need to import the function of module functools .

    
24.02.2017 / 12:56