列表包含全名和简称。我想将以下列表中的短名称扩展为其全名。例如。 Pollard 应更改为 Kieron Pollard,Starc 应更改为 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)
输出:
['Pollard', 'Kieron Pollard', 'Mitchell Starc', 'Pollard', 'Starc']
['Kieron Pollard', 'Kieron Pollard', 'Mitchell Starc', 'Kieron Pollard', 'Mitchell Starc']
上面的方法效果很好。我想知道是否有更好、更有效的方法来做同样的事情。
最佳答案
只需将实际名称及其替换放在字典中,然后使用列表理解通过在字典中查找名称来重建玩家名称。
传递给 names.get
方法的第二个参数是当第一个参数在字典中不存在时返回的默认值。
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']
关于python - 如果字符串包含另一个字符串,则将字符串替换为同一列表中的另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23580812/