1

I want to search for elements of namelist in banklist, and if an element is found in banklist, return that element as well as the element after it.

So for example: Namelist: 'John Doe', 'Jack Black'. Banklist: 'John Doe', '9134', 'Richard Pitt', '1652', 'Jack Black', '9145', 'Bob Brand', '6523'

I want this returned: 'John Doe,9134', 'Jack Black,9145'

To this end, I have written the following. It works, but I don't know how to iterate it, so that it searches for all the elements that overlap, instead of stopping after the first.

Result: 'John Doe,9134'. Desired result: 'John Doe,9134', 'Jack Black,9145'.

f = open('namelist.txt', 'r') namestring = f.read() f.close() f = open('testsheet.csv', 'r') bankstring = f.read() f.close() namestring = namestring.replace(", ", ",") namelist = namestring.split(",") banklist = bankstring.split("\n") bankstring = ','.join(banklist) banklist = bankstring.split(",") n = banklist.index(namelist[1]) res = banklist[n] + "," + banklist[n+1] print(res) 
0

1 Answer 1

1

Simplifying the problem, using the enumerate on the bank_list and printing the name and the number if the element from it exists in the name_list:

name_list = ['John Doe', 'Jack Black'] bank_list = ['John Doe', '9134', 'Richard Pitt', '1652', 'Jack Black', '9145', 'Bob Brand', '6523'] for ind, elem in enumerate(bank_list): if elem in name_list: print(elem, bank_list[ind + 1]) 

OUTPUT:

John Doe 9134 Jack Black 9145 
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I wanted to ask another question but it didn't work in a comment. Could you look at the edit please?
@user2296226 there is nothing in the edit, if you want to ask another question please make it a separate one! Would love to help again cheers ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.