Reputation: 55
I have a list of lists and I want to return the index of the element that a user has searched for. Here is my code so far:
player_list = [[Bruce Wayne, 5, 5, 0, 0, 100, 15], [Jessica Jones, 12, 0, 6, 6, 10, 6], [Johnny Rose, 6, 2, 0, 4, 20, 10], [Gina Linetti, 7, 4, 0, 3, 300, 15], [Buster Bluth, 3, 0, 2, 1, 50, 1]]
def find_player(player_list, player_name):
for player_info in player_list:
if player_name == player_info[0]:
x = player_info.index(player_name)
elif player_name == player_info[0]:
x = -1
return x
player_name = str(input("Please enter name:"))
y = find_player(player_list, player_name)
if y == -1:
print(player_name, "was not found in player list")
else:
print(player_list[y])
The problem is the the index that is returned is always 0, so if the user searches for "Bruce Wayne", it works fine but if they search for say, "Jessica Jones", the code outputs "Bruce Wayne".
Upvotes: 2
Views: 65
Reputation: 75
Here's one way to do it:
player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15],['Jessica Jones', 12, 0, 6, 6, 10, 6],['Johnny Rose', 6, 2, 0, 4, 20, 10],['Gina Linetti', 7, 4, 0, 3, 300, 15],['Buster Bluth', 3, 0, 2, 1, 50, 1]]
def find_player(player_list, player_name):
for i, player_info in enumerate(player_list):
if player_name == player_info[0]:
return i
return -1
player_name = str(input("Please enter name:"))
y = find_player(player_list, player_name)
if y == -1:
print(player_name, "was not found in player list")
else:
print(player_list[y])
Output
Please enter name: Johnny Rose
['Johnny Rose', 6, 2, 0, 4, 20, 10]
Upvotes: 2
Reputation: 12241
Use
for iplayer, player_info in enumerate(player_list):
and return iplayer
instead of x
, inside the loop (so exit the function prematurely). Put a default return -1
at the end. That will return the index of the actual sublist in the main list.
Upvotes: 1