How to get the index value of a list in Python?

Asked

Viewed 3,780 times

2

I’m trying to find a way to fit in a salary amount, which is my variable sal, at an interval. I have 8 intervals:

  1. $200 - $299
  2. $300 - $399
  3. $400 - $499
  4. $500 - $599
  5. $600 - $699
  6. $700 - $799
  7. $800 - $899
  8. $900 - $999

But I can’t use several if aligned. So I put the maximum values in a list and thought to go comparing item by item of the list with the value of the salary and then take the list value index as in the code below:

lista = [299,399,499,599,69,799,699,999]

valor_bruto = float(input("Digite o valor bruto das vendas semanais do funcionário"))
sal = 200 + 0.09*valor_bruto #valor do salario

for n in lista:
    if sal < n:
        c = lista.index(n) #guarda valor do índice em que se encontra o valor do salário

print("O funcionário está no intervalo entre",(lista[c]-99) ,lista[c])

But the code is not getting the correct index value. And I can’t figure out the error.

2 answers

3


On your list there is a value 69, but I believe you meant 699. And after the 799, place 899 (for before I was 699).


It is possible to go through a list and access at the same time the index and its element, using enumerate:

lista = [299, 399, 499, 599, 699, 799, 899, 999]
valor_bruto = float(input("Digite o valor bruto das vendas semanais do funcionário"))
sal = 200 + 0.09 * valor_bruto # valor do salário
for i, valor in enumerate(lista):
    if sal < valor:
        indice = i # encontrei o índice
        break # saio do loop
print(f"O funcionário está no intervalo entre {lista[indice] - 99} e {lista[indice]}")

That is, when I find the index, I can already leave the for, using break. Then, just print the values, as you were doing. I used f-strings (the string with a f before the quotation marks), which are available from Python 3.6, but if you are using a previous version, you can also do so:

print("O funcionário está no intervalo entre {} e {}".format(lista[indice] - 99, lista[indice]))

Call index to get the index also works, but this will cause the list to be covered again, until you find the index of the element in question. But this is unnecessary if you go through the list with enumerate, because you will already have the index when its value is found.


Another detail is that subtracting 99 may work for this specific case, but what if the salary ranges are different? (as for example [299, 499, 1999])

In this case, a more generic way is to check if the index is the first, last or other in the middle of the list, and format the message according to each case:

for i, valor in enumerate(lista):
    if sal < valor:
        indice = i # encontrei o índice
        break
else:
    indice = - 1

if indice == 0: # primeira faixa
    print(f"O funcionário está no intervalo abaixo de {lista[indice]}")
elif indice == - 1: # depois da última faixa
    print(f"O funcionário está no intervalo acima de {lista[indice]}")
else: # alguma faixa do meio
    print(f"O funcionário está no intervalo entre {lista[indice - 1] + 1} e {lista[indice]}")

Now I’ve included a else in the for (yes, in Python a for may have a else associated), which indicates the case where the salary does not fall into any of the bands. That is, if the salary is not lower than any of the values on the list, it means that it is greater than all. In this case, it never enters the if sal < valor, the break is not called, and this causes it to fall into the else. In this case, I choose the index for -1.

Then, just check which range of values the index corresponds to. If it is the first (index is zero), I just state that the salary is below such value (there is no previous value, so subtracting 99 or any other value makes no sense here).

If it is -1 I know that the salary is higher than all the values on the list, so suffice it to say that it is above the last value (and I take advantage of the fact that lists accept negative indexes: in this case, -1 corresponds to the last element).

Finally, if the value is in any of the middle bands in the list, just take the previous value and add 1 (instead of subtracting 99), so you have a reliable way to get the range, regardless of the values in the list.


Obviously, the list values must be in ascending order for this to work. If you want to ensure that it is sorted, you can use sorted:

lista = sorted(lista)
for i, valor in enumerate(lista):
    ...

Or even the method sort:

lista.sort()
for i, valor in enumerate(lista):
    ...

The difference is that sorted(lista) returns another list (i.e., you have the option to keep the original intact by assigning the result to another variable), while lista.sort() modifies its own lista.


Alternative

An alternative is to use range to save the breaks:

intervalos = [ range(0, 300), range(300, 400), range(400, 500), range(500, 600), range(600, 700), range(700, 800), range(800, 900), range(900, 1000) ]
sal = ... # ler salário com input(), etc
for r in intervalos:
    if sal in r:
        print(f"O funcionário está no intervalo entre {r.start} e {r.stop - 1}")
        break;
else:
    print(f"O funcionário está no intervalo acima de {intervalos[-1].stop}")

A detail of range is that the first value is included, but the second value is not. So range(300, 400) includes all numbers between 300 and 399.

Then I do if sal in r to test if the salary is contained in the range. If the salary is not in any of the ranges, the code falls on the else (recalling again that this else is from for, not of if, as explained above).

0

To fix the problem, first fix the values in your list. Then set the conditional if to find out if sal is greater than or equal to n - 99 and less than or equal to n. If it is, it receives the index of the value n on the list and exits the block for. See below:

lista = [299,399,499,599,699,799,899,999]

valor_bruto = float(input("Digite o valor bruto das vendas semanais do funcionário: "))
sal = 200 + 0.09*valor_bruto #valor do salario

for n in lista:
    if n - 99 <= sal <= n:
        c = lista.index(n)
        break
print("O funcionário está no intervalo entre",lista[c]-99 ,"e",lista[c])

Browser other questions tagged

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