简体   繁体   中英

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.')

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

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]]

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