Python: encontrar la posición del valor en una lista y generar una nueva lista
Frecuentes
Visto 620 equipos
1
Currently learning python in my course and I'm a little confused on this part, unfortunately my next prac isn't until next week so I thought I'd ask here.
We're supposed to write a function called find() that takes a list, searches for the value in the list and returns as a new list of the positions in the list the number was found. Eg:
list = 2, 3, 7, 2, 3, 3, 5
number = 3
la salida sería: 0, 4, 5
The question requires us to use a loop but not to use built-in functions, slice expressions, list methods, or string methods unless specified, with the only ones specified for this part being: .append()
y range()
.
We're given a file we're not allowed to edit:
import test_lists
list_A = ['q', 'w', 'e', 'r', 't', 'y']
print(test_lists.find(list_A, 'r'))
print(test_lists.find(list_A, 'b'))
From what I've attempted in a file named test_lists, the output gives <function find at 0x0000000003B89D90>
:
def find(list1, listValue):
findList = 0
for x in range(findList):
findList.find(list1, value)
return find
anyone able to please push me in the right direction and explain it to me? We were told we could use .append()
but I don't seem to understand how that would fit into this situation as from what I am aware append only adds to to the string. I feel like I'm pretty far off track.
Muchas Gracias
4 Respuestas
2
Usar enumerate
y lista de comprensión:
>>> lst = 2, 3, 7, 2, 3, 3, 5
>>> number = 3
>>> [i for i, x in enumerate(lst) if x == number]
[1, 4, 5]
>>> list_A = ['q', 'w', 'e', 'r', 't', 'y']
>>> [i for i, x in enumerate(list_A) if x == 'r']
[3]
Por cierto, no uses list
as a variable name. It shadows builtin type/function list
.
ACTUALIZAR
sin uso enumerate
:
>>> lst = 2, 3, 7, 2, 3, 3, 5
>>> number = 3
>>> [i for i in range(len(lst)) if lst[i] == number]
[1, 4, 5]
contestado el 28 de mayo de 14 a las 13:05
thanks for the reply however as stated in my question we can't use built in functions which would include enumerate()
. We can only use range()
función y .append()
method to get the output. - Asphyxiate9
Well then the quick change is: [i for i in range(len(lst)) if lst[i] == number]
- RemolachaDemGuise
1
Will this do ?
def find(list1, listValue):
found = []
for index in range(0,len(list1)):
if list1[index]==listValue:
found.append(index)
return found
contestado el 28 de mayo de 14 a las 13:05
0
I guess you can't use enumerate
?
Then, you you have to do the same thing by yourself : iterate over the indexes of the list and for each index, see if the element is the expected element. If it is, you had the index into your result list :
expected_element = 3
my_list = [...]
result_list = []
for i in range(len(my_list)):
if my_list[i] == expected_element:
result_list.append(i)
It's not very pythonic but if you have so much contraint, i think it's good
Y si no puedes usar len(my_list)
, you can get the size by iterate over a first time :
def size(l):
s = 0
for _ in l:
s += 1
return s
contestado el 28 de mayo de 14 a las 13:05
0
A list comprehension would be the most Pythonic way to do this. But writing it explicitly for instructional purposes, here is another way to do it.
def find(number, numList):
indexMatches = [] # initialize your index array
for index in range(len(numList)): # iterate over the list of values
if number == numList[index]: # compare the number against the current value
indexMatches.append(index) # if they match, add it to the index array
return indexMatches # return the list of indexes where matches occured
find(3, [2,3,7,2,3,3,5])
Salida
[1, 4, 5]
contestado el 28 de mayo de 14 a las 13:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas python list or haz tu propia pregunta.
Quieres decir
1, 4, 5
? - falsetruHm, I assumed it would count up from 0 and not from 1. That was just an example anyway. Looking to find the position of r in that list in the part below - Asphyxiate9