1

A list has a mixture of full names and their short names. I want to expand the short names to their full name in a list like below. Eg. Pollard should be changed to Kieron Pollard and Starc should be changed to Mitchell Starc.

players = ['Pollard', 'Kieron Pollard', 'Mitchell Starc', 'Pollard', 'Starc']

print(players)
for i, s in enumerate(players):
    for p in players:
        if len(p) > len(s) and s in p: # Different string
            players[i] = p
print(players)

Output:

['Pollard', 'Kieron Pollard', 'Mitchell Starc', 'Pollard', 'Starc']
['Kieron Pollard', 'Kieron Pollard', 'Mitchell Starc', 'Kieron Pollard', 'Mitchell Starc']

The above method works great. I want to know if there is a better and a efficient way of doing the same.

2 Answers 2

2

Just have the actual name and its replacement in a dictionary and using List Comprehension reconstruct the player names by looking up the names in the dictionary.

The second argument passed to names.get method is the default value to be returned if the first argument doesn't exist in the dictionary.

names = {'Pollard': 'Kieron Pollard', 'Starc': 'Mitchell Starc'}
print [names.get(player, player) for player in players]
# ['Kieron Pollard', 'Kieron Pollard', 'Mitchell Starc', 'Kieron Pollard', 'Mitchell Starc']
Sign up to request clarification or add additional context in comments.

3 Comments

names = {p.split()[-1] : p for p in players if ' ' in p}
@Kiwi player names can be three words sometimes
If the short name is always the last one, it's ok: ' ' in p stands for at least two words, p.split()[-1] extracts the last one
1

I would sort the players by their lengths and pass on the from the longest to the shortest - breaking the inside loop when ever getting to a containment.

Also, note that in the way you check the containment - "a" is in "ab". Make sure that this is what you want.

1 Comment

about the containment, yes I can be sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.