pythonnovice16 pythonnovice16 - 5 months ago 22
Python Question

How to merge names with common elements in list?

In a list called 'common', I have a bunch of names that have common elements. For instance, my list has these names in it

common = ['Jeremy Paul', 'Paul Stevens', 'John Jordan', 'Jordan Smith',
'Jordan Walker', 'Walker Marshall']


I want to be able to merge all the names that have common elements in the most Pythonic way (don't want to have to use libraries or list comprehension unless necessary). The common elements are the ones that are first names in one string and last names in the following string. As an example, this is what I want the result to be:

result = ['Jeremy Paul Stevens', 'John Jordan Smith', 'John Jordan Walker',
'Jordan Walker Marshall']


I only want to have three words in each string, so no
John Jordan Walker Marshall
or anything with more than three names.

Is there some way I can do this in Python? I'm assuming I need to use some loop or form of iteration to go through each item in
common
, or maybe I have to use regular expressions to achieve the desired result. I'd appreciate any pointers in the right direction, thanks!

Answer

An approach: Split each string up into constituent parts, pair up parts of every item, and check if the first pair ends with the first part of the second pair -- if so insert into a list.

Something like:

>>> common = ['Jeremy Paul', 'Paul Stevens', 'John Jordan', 'Jordan Smith', 
... 'Jordan Walker', 'Walker Marshall']
>>> parts = [x.split() for x in common]
>>> [" ".join([x[0], x[1], y[1]]) for x in parts for y in parts if x[1] == y[0]]
['Jeremy Paul Stevens', 'John Jordan Smith', 'John Jordan Walker', 'Jordan Walker Marshall']