banner

© 2004-21 ict4u.net

Finding Text a 2D List

Ths code snippet below shows you how find an data in a 2D list
This is not as easy as a 1D list as each sub ‐ list has to opened and inspected

#Author: A Knifton
#Date: 16 Mar 2019
#Purpose: Search fro string in a 2d list and return the indices in a list

players = [['Amanda Vasquez', 'Jalapenos', 'London', 121],
           ['Ben Cooley', 'Hot Shots', 'Birmingham', 90],
           ['Toby Contreras', 'Cobra', 'Exeter', 24],
           ['Diego Ward', 'Mavericks', 'Bristol', 183],
           ['Mireya Garrett', 'Captivators', 'London', 40],
           ['Semaj Fox', 'Hot Shots', 'Exeter', 151]]

print("Team Players:")
for data in players:
	print(data)

myChoice = input("Enter the item find: ").title()

# now make a new list of indices using a list comprehension
# the for loop iterates through the list only population the new list if the text string is found in the sublist
found = [[index, subList.index(myChoice)] for index, subList in enumerate(players) if myChoice in subList]

#found now comprises a list of lists where the data was found giving the index of the out and inner list
print(found)