Bobby Lee
Bobby Lee

Reputation: 15

Searching for an element in a nested list and printing it out

I have a nested list that looks like this

[['ID', 'Name'], ['E001', 'Marcus Tan'], ['E002', 'Mary Tay'], ['E003', 'Patrick Goh'], ['E004', 'Joey Lim'], ['E005', 'Edward Lim']]

And I have to search for a part of their name, for example ('Ma')

and the supposed outcome is supposed to be

Enter any part of name: Ma

Emp ID  Name 

E001    Marcus Tan 

E002    Mary Tay

This is my code so far

def search_emp():
    name = input('Enter any part of name: ')
    emp_list = []
    print('{:<5} {:>7}'.format('Emp ID', 'Name'))
    print('-------- -----------------')
    with open('Assignment_Data1.csv') as f:
        if name in emplist:
            print('{}'.format(name))
        else:
            print('Sorry there are no such employees.')

Upvotes: 1

Views: 59

Answers (2)

rafaelc
rafaelc

Reputation: 59274

For lots of rows, can use pandas (makes really easy to visualize the data ;))

import pandas as pd

>>> df = pd.DataFrame(values, columns=['ID','name'])
>>> df[df.name.str.contains('Ma')]

    ID  name
1   E001    Marcus Tan
2   E002    Mary Tay

Upvotes: 2

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Try this:

a=[['ID', 'Name'], ['E001', 'Marcus Tan'], ['E002', 'Mary Tay'], ['E003', 'Patrick Goh'], ['E004', 'Joey Lim'], ['E005', 'Edward Lim']]
b=input("Enter any part of name: ")
print("""\nEmp ID  Name """)
[print('   '.join(e)) for e in a if b in e[1]]

Upvotes: 1

Related Questions