1
I need to replace values in a list of agreements with some criteria.
Criteria:
- if the value is an integer and less than the reported value is replaced by -1
- 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
andint
, already are when you receive the input and cast for those guys. You are with9999
in the code but in the explanation/results you say999
, must be a typo/mistake.– Miguel
Miguel, already corrected the error is actually 9999.0.
– Bruno
I don’t see anything wrong, maybe you just want one
elif(...)
instead of the secondif
, https://ideone.com/MVnftr so as not to enter the twoifs
because in that case the secondif
will prevail even if the first one checks out– Miguel
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.
– Bruno
I thank you all .
– Bruno
@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. Useisinstance
for such.– Woss