Reputation: 22926
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.
Upvotes: 1
Views: 50
Reputation: 6181
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.
Upvotes: 1
Reputation: 239443
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']
Upvotes: 2