john johns
john johns

Reputation: 167

python: compare part of a string from a list of strings to items in another list and generate a third list

Given a list of names (list A) with respective titles, I am iterating through it to determine the title of each entry (Mr, Mrs, Dr etc...) by comparing it to another list (list B) containing exactly these titles and creating another list (list C) with their titles only. In case there is a name in list A whose title is not listed in list B, then list C should be filled with the name in full taken from list A.

The following code:

A = [
    'Anna, Mrs. James (Nadia Elf)',
    'Martin, Mr. Michael',
    'Barese, Mr. Alfred',
    'Amalfi, Mrs. Abby (J E V)',
    'Manuel, Dr. Louis'
]
C=[]
B=['Mrs.','Mr.','Dr.']
for i in A:
    for j in B:
        if j in i:
            C.append(j)
      
print(C) # prints ['Mrs.', 'Mr.', 'Mr.', 'Mrs.', 'Dr.']

prints the right output and that is because all titles contained in A, show up in B, but if I slightly change the code above by editing the last item in list A to 'card.' instead of 'Dr'

A = [
    'Anna, Mrs. James (Nadia Elf)',
    'Martin, Mr. Michael',
    'Barese, Mr. Alfred',
    'Amalfi, Mrs. Abby (J E V)',
    'Manuel, card. Louis'
]
C=[]
B=['Mrs.','Mr.','Dr.']
for i in A:
    for j in B:
        if j in i:
            C.append(j)
        else:
            C.append(i)
print(C)

I would like to see this output ['Mrs.', 'Mr.', 'Mr.', 'Mrs.', 'Manuel, card. Louis']

but instead, it prints

['Mrs.', 'Anna, Mrs. James (Nadia Elf)', 'Anna, Mrs. James (Nadia Elf)', 'Martin, Mr. Michael', 'Mr.', 'Martin, Mr. Michael', 'Barese, Mr. Alfred', 'Mr.', 'Barese, Mr. Alfred', 'Mrs.', 'Amalfi, Mrs. Abby (J E V)', 'Amalfi, Mrs. Abby (J E V)', 'Manuel, card. Louis', 'Manuel, card. Louis', 'Manuel, card. Louis']

How can this be solved?

Upvotes: 0

Views: 352

Answers (1)

ujjaldey
ujjaldey

Reputation: 439

This should work. In your code, for every elements in B, it tries to find it in A - and if not matched, still appends i to c

A = [
    'Anna, Mrs. James (Nadia Elf)',
    'Martin, Mr. Michael',
    'Barese, Mr. Alfred',
    'Amalfi, Mrs. Abby (J E V)',
    'Manuel, card. Louis'
]
C=[]
B=['Mrs.','Mr.','Dr.']
for i in A:
    contains = False
    for j in B:
        if j in i:
            contains = True
            break
            
    if contains:
        C.append(j)
    else:
        C.append(i)
print(C)

Output: ['Mrs.', 'Mr.', 'Mr.', 'Mrs.', 'Manuel, card. Louis']

Upvotes: 2

Related Questions