list value to a variable, Python

Asked

Viewed 1,084 times

2

I want to create a list, and assign to a variable the value referring to the positioning of that list

For example list = ["a", "b", "c"]

Let’s say the priest gives me the letter "c"

I want a variable n that gets the number 2

3 answers

2

you can create a function that receives the list and the element you want to think will return to its position.

    def ref(lista, elemento):
        for i in range(len(lista)):
            if lista[i] == elemento:
                return i
        return False

    # exemplo de uso 

    lista = ['a','b','c']
    n = ref(lista,'c')
    print('n =', n)

if you do not find the element it returns a False.

  • But it turns out I want to draw a random element from a list, and assign its value to a variable. I really want the value of the position, in this example I put, I want the value "2" (which is the number of the position) in a variable

  • in the example I gave you put the list and put the element and it returns the position it is in the list, if it does not find it returns false. if you want a random value you can import Random and use Random.Choice(list) then it takes a random element from the list. in case I put the value of the position in variable n.

  • 2

    Python lists have the method .index who already does what you suggest. Also, for i in range(len...): and definitely not idiomatic for Python, and should not be present in an answer to advise beginners.

  • If there is something wrong with my answer let me know that I will try to help you in the best way possible.

2

# Importa o método choice do módulo random que gera elementos randômicos(aleatórios)

from random import choice

# Cria uma lista

lista = ['a', 'b', 'c']              

# utiliza o método random para retornar um elemento aleatório da sua lista

elemento = choice(lista)            

# Utiliza o metódo index dos objetos de tipo list ara retorna o índice do elemento retornado

indice = lista.index(elemento)   

# Imprime o elemento e seu índice

print(elemento, indice)


'''

Esse algoritmo só funciona se sua lista não possuir elementos de mesmo valor 
pois o metódo index dos objetos tipo list retorna
a primeira ocorrência do elemento.

Exemplo:

'''

lista = ['a', 'b', 'c', 'a']

elemento = 'a'

indice = lista.index(elemento)

print(elemento, indice)

'''

Retorna o índice de valor 0 e não 3 mesmo 'a' aparecendo tanto em indice 0 
como em 3, ou seja o método index retorna a
primeira ocorrência do elemento lembre-se disso

'''

0

An easier way for you to do that is :

 l=['nathan','guilherme','otavio','ana']

# Lista que irá receber o indice
lista_enumerada = []

# for com enumerate, para que possamos ver o seu indice
for a,b in enumerate(l):
    lista_enumerada.append(a) # adicionando o valor a(indice) a lista

#armazenamento da escolha randomica
choice = random.randint(0,3)
n = l[choice] # Random na lista principal
print(n)
print(lista_enumerada[choice]) 
  • Instead of enumerate, a simpler way to have the index list is: lista_enumerada = list(range(len(l)))

  • Thanks! I had not thought to use this method of len to have a list only of indices, I only learned the form of the enumerate. This will facilitate my next Cod’s. Thank you very much

Browser other questions tagged

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