如果string包含另一个字符串,则将字符串替换为同一列表中的另一个字符串

时间:2014-05-10 12:01:28

标签: python python-2.7

列表中包含全名和短名称的混合。我想在下面的列表中将短名称扩展为其全名。例如。 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']

上述方法效果很好。我想知道是否有更好,更有效的方法来做同样的事情。

2 个答案:

答案 0 :(得分:2)

在字典中使用实际名称及其替换,并使用List Comprehension通过查找字典中的名称来重建播放器名称。

传递给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']

答案 1 :(得分:1)

我会根据他们的长度对玩家进行排序,然后从最长到最短的时间进行传递 - 在进入收容时打破内部循环。

另外,请注意检查收容的方式 - " a"在" ab"。确保这是你想要的。

相关问题