I have a nested list called players as shown below:
players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ]
I want to be able to search by Player name (PlayerA, PlayerB, etc) using an input statement and if the search matches an item, then it prints out the entire item. How would I go about doing this, I am trying to learn different methods.
search = input("Please enter the players name")
for item in players:
if item == search:
print(item)
else:
print("item not found")
When I do the above it keeps printing item not found.
Many Thanks in Advance.
Remove items from a Nested List. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item. If you don't need the removed value, use the del statement.
Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element. Here, [a,b], [c,d], and [e,f] are separate lists which are passed as elements to make a new list. This is a list of lists.
The reason that it's printing "item not found" is because you are comparing a sublist to the string to find, e.g.,
["PlayerA", "10", "20"] == "PlayerA"
which, of course, is false. You need to extract the name from each sublist.
One way you could do this is to use filter
like so:
filter(lambda record: record[0] == "PlayerA", players)
This will return a list of the records with a 0th element matching "PlayerA".
if item == search:
This conditional won't succeed because item
is ["PlayerA", "10", "20"]
, and search
is "PlayerA"
. A list won't ever compare equal to a string.
Try comparing search
against the first element of item
specifically.
if item[0] == search:
Filter the players using a list comprehension, which compares the first item from each sub list in players
with the player name from search
:
players = [["PlayerA", "10", "20"], ["PlayerB", "15", "30"], ["PlayerC", "15", "30"] ]
search = input("Please enter the players name: ")
result = [player for player in players if player[0] == search]
if result == []: # or if not result
print("item not found")
else:
print(result)
You need to access to first element or your nested list. Like this:
for player in players:
if player[0] == input:
return player
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With