Say I have a list of names like so:
names = ['Ted Cruz', 'Donald Trump', 'Cruz']
I want to replace the third element, 'Cruz', with its corresponding full name found in the first element. How can I achieve this in a general sense, If I have a very long list of names and can't manually check?
CodePudding user response:
I assume, full names have space between first name and last name, so I do this:
list_of_partial_names = list()
partial_name_to_full_name = dict()
names = ['Ted Cruz', 'Donald Trump', 'Cruz']
for name in names:
parts_of_name = name.split()
if len(parts_of_name) == 1: # it's not a full name
list_of_partial_names.append(parts_of_name[0])
else:
for part in parts_of_name:
partial_name_to_full_name[part] = name
# To replace all partial names with full name
for index,name in enumerate(names):
if name in partial_name_to_full_name:
names[index] = partial_name_to_full_name[name]
print(names)
Output:
['Ted Cruz', 'Donald Trump', 'Ted Cruz']