How do I find the position of an item in a list?

3

I am writing a program that receives a specific amount of values, and returns the lowest value in the list and its position. It is as follows:

quantidade = int(raw_input())
numeros = raw_input()
NumerosNaLista = numeros.split()
if len(NumerosNaLista) == quantidade:
    MenorValor = min(NumerosNaLista)
    print "Menor valor:", MenorValor

I tried to use find to find the position of the lowest value in NumerosNaLista , but it does not work. How to proceed?

    
asked by anonymous 10.04.2016 / 00:18

5 answers

4
#!/usr/bin/env python
#*-* coding: utf-8 *-*

numbers = raw_input()

# gera um vetor de numeros atravez da string
n_list = [ int(x) for x in numbers.split() ]

n_min = min(n_list)
n_pos = n_list.index(n_min) # pega a posição do valor n_min

print "Menor valor: %s" % n_min
print "Posição: %" % n_pos
    
10.04.2016 / 00:49
5

You can implement your algorithm using loop, in this case while . Here's how this example looks:

lista = []
i = 0
quantidade = int(raw_input('Qtd: '))

while (i < quantidade):
    numero = input("Valor: ")
    i += 1
    lista.append(numero)

print 'Indice do menor valor:', lista.index(min(lista))

Entry (number of numbers to insert into the list):

  

3

Entry (values):

  

21
  33   -21

Output (lowest value index):

  

2

The index() method finds the index of an item in a given list, passing the desired item as an argument, which in this case was the lowest value of the list returned by the min() method.

I'd like to refer to documentation to learn more about methods and a read on manipulation of lists in Python .

    
10.04.2016 / 03:04
0

I was able to do this:

quantidade = int(raw_input())
numeros = raw_input()
NumerosNaLista = numeros.split()
if len(NumerosNaLista) == quantidade:
    MenorValor = min(NumerosNaLista)
    print "Menor valor:", MenorValor
    lista = numeros.replace(" ", "")
    MenorValor = min(lista)
    posicao = lista.find(MenorValor)
    print "Posicao:", posicao

It worked, and I believe it is right. If there is an error, please let the viewer know.

    
10.04.2016 / 00:36
0

Another way:

menor_ate_agora = None
quantidade = int(raw_input())
numeros = raw_input()
NumerosNaLista = numeros.split()
if len(NumerosNaLista) == quantidade:
    for valor in NumerosNaLista:
        if menor_ate_agora is None:
            menor_ate_agora = valor
        elif valor < menor_ate_agora:
            menor_ate_agora = valor
    print "Menor valor:", menor_ate_agora
    lista = numeros.replace(" ", "")
    MenorValor = min(lista)
    posicao = lista.find(MenorValor)
    print "Posicao:", posicao
    
10.04.2016 / 00:59
-2

Simple like this ...

print('Posição: {}'.format(NumerosNaLista.index(MenorValor))
    
30.10.2018 / 19:16