简体   繁体   中英

Searching elements in a 2D list in Python

I have a two-dimensional list that has about 1000 elements. It looks something like this:

myList = [['1', 'John', 'Doe', 'jdoe@email.com', '234-35-2355'], ['2', 'Rebecca', 'Swan', 'rswan@email.com', '244-56-4566'], ['3', 'Terry', 'Smith' 'tsmith@email.com', '345-45-1234']]

Index [1] is their first name, and I want to search this list (that has 1000 people, only used 3 for simplicity), to see if they are in the list, and if they are, print their information, without using Numpy.

So far I have:


firstName = input('Enter the first name of the record: ')

row = len(myList)

found = False
for row in my list:
    for element in row:
        if element == firstName:
            found = True
            break

    if found:
        break

if found:
    print('User ID: ', myList[0])
    print('First Name: ', myList[1])
    print('Last Name: ', myList[2])
    print('Email: ', myList[3])
    print('Login IP: ', myList[4])

else:
    print('There is no record found with first name', firstName)

Now this seems to be working to find if the person is there or not, however I am having trouble with printing the information after, because I do not know how to find the index of the person, I believe if I had the index the print would be something like myList[index][1]

EDIT: Okay I see that it was a simple fix of changing myList[1] to row[1]. Now say you search a name and two people in the list have the same name and you want to print both sets of information, how would I go about that?

One of many possible ways:

def findByName(name, lst):
    return filter(lambda x: x[1] == name, lst)

for item in findByName("John", myList):
    print(item)

This yields

['1', 'John', 'Doe', 'jdoe@email.com', '234-35-2355']


Or directly with a listcomp:

 persons = [entry for entry in myList if entry[1] == name]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM