I have a list of names of persons and I want to extract the title and the last name. I have written the following code:
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
def split_title_and_name(person):
for i in person:
title = [i.split(' ')[0] for i in person]
lname = [i.split(' ')[-1] for i in person]
return (title + lname)
The output I'm getting is :
['Dr.',
'Dr.',
'Dr.',
'Dr.',
'Brooks',
'Collins-Thompson',
'Vydiswaran',
'Romero']
The result which I want is like this:
['Dr.Brooks' , 'Dr.Collins-Thompson' ...]
title contains a list of all first names lname contains a los of all the last names Seems like you need a zip operation
print("Zip:")
for x, y in zip(a, b):
print(x, y)
Instead of two separate lists, just do it all at once:
names = [i.split(' ')[0] + i.split(' ')[-1] for i in people]
The way you're doing it, you're trying to add two lists together - what you want is to add the two strings together as you're making the list. You can do this all in one line, as above - the outer for
loop isn't even necessary.
Seems like you just need to split in a comprehension and then pull out the first and last in another one:
people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
[n[0]+n[-1] for n in [p.split(' ') for p in people]]
>>> ['Dr.Brooks', 'Dr.Collins-Thompson', 'Dr.Vydiswaran', 'Dr.Romero']
You could also split with a regex, although this is probably overkill for this:
import re
regex = re.compile("\s.+\s")
[''.join(regex.split(s)) for s in people]
>>> ['Dr.Brooks', 'Dr.Collins-Thompson', 'Dr.Vydiswaran', 'Dr.Romero']
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.