Substituting values in a list

Asked

Viewed 3,978 times

1

I need to replace values in a list of agreements with some criteria.

Criteria:

  1. if the value is an integer and less than the reported value is replaced by -1
  2. if the value is a floating point number and greater than the reported number replace by 9999.0.

Code:

lista =[-9 ,20.5, 6 ,10.8, 10, 8.0, 45, -99.6, 12, -54.7]
valores = input('Digite um valor inteiro e um valor em ponto   flutuante:').split()
num1 = int((valores[0]))
num2 = float((valores[1]))
for i in range(len(lista)):
    if int(num1):
        if lista[i] < num1:
            lista[i]= -1
    if float(num2):
        if lista[i] > num2:
            lista[i] =9999.0

print(lista)

Correct exit would be:

-1 9999.0 -1 9999.0 10 8.0 45 -99.6 12 -54.7

The output of my code is:

-1, 9999.0, -1, 9999.0, 9999.0, -1, 9999.0, -1, 9999.0, -1

Friends I managed to solve as follows.

Code:

 lista =[-9 ,20.5, 6 ,10.8, 10, 8.0, 45, -99.6, 12, -54.7]
 valores = input('Digite um valor inteiro e um valor em ponto   flutuante:').split()
 num1 = int((valores[0]))
 num2 = float((valores[1]))
 for i in range(len(lista)):
    if type(lista[i]) is int and lista[i] < num1:
       lista[i] = -1
    elif type(lista[i]) is float and lista[i] > num2:
       lista[i] = 9999.0
 print(lista)
  • No need to do ifs float and int, already are when you receive the input and cast for those guys. You are with 9999 in the code but in the explanation/results you say 999, must be a typo/mistake.

  • 1

    Miguel, already corrected the error is actually 9999.0.

  • 1

    I don’t see anything wrong, maybe you just want one elif(...) instead of the second if, https://ideone.com/MVnftr so as not to enter the two ifs because in that case the second if will prevail even if the first one checks out

  • Hello Miguel, the code is not giving the correct exit, I tried with Elif but it did not work, but thanks for participating, I go to fight.

  • I thank you all .

  • @Bruno Just commenting, it is not recommended to use the type to check the type as it does not check inheritance. As in Python typing is dynamic, this is a detail that should always be taken into account. Use isinstance for such.

Show 1 more comment

1 answer

1


A little more streamlined than your solution

lista =[-9 ,20.5, 6 ,10.8, 10, 8.0, 45, -99.6, 12, -54.7]
valor_inteiro, valor_float = [float(x) for x in input('Digite um valor 
inteiro e um valor em ponto flutuante:').split()]

for i in range(len(lista)):
    if isinstance(lista[i], int) and lista[i] < valor_inteiro:
        lista[i] = -1
    if isinstance(lista[i], float) and lista[i] > valor_float:
        lista[i] = 9999.0

print(lista)
  • Thanks Anderson Carlos Woss, helped me a lot this teaching.

Browser other questions tagged

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