Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Searching Nested Lists

Tags:

python

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.

like image 516
PythonNewBee Avatar asked Jun 27 '16 13:06

PythonNewBee


People also ask

How do I remove an element from a nested list in Python?

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.

Can you have a list within a list Python?

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.


4 Answers

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".

like image 92
user4601931 Avatar answered Oct 16 '22 19:10

user4601931


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:
like image 40
Kevin Avatar answered Oct 16 '22 18:10

Kevin


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)
like image 3
RoadRunner Avatar answered Oct 16 '22 19:10

RoadRunner


You need to access to first element or your nested list. Like this:

for player in players:
    if player[0] == input:
        return player
like image 2
user2393256 Avatar answered Oct 16 '22 17:10

user2393256