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

标签 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']

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

最佳答案

只需将实际名称及其替换放在字典中,然后使用列表理解通过在字典中查找名称来重建玩家名称。

传递给 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/

相关文章:

linux - python 2.7 : How do I read single keypress in Linux (Including special characters)?

python - 在特定键值处开始字典 for 循环

python - 正确打印列表条目剂量格式

python - 使用 python 在 Windows 中更改鼠标指针速度

包中 Windows 上的 Python 多处理

python - BeagleBone 上的 Python 包 Kivy 出现问题

Python 柯里化(Currying)任意数量的变量

python - 如何通过 class 属性包含空格的 css 选择器匹配特定标签?

python - 数据框内的 Pandas 转置

python - Selenium Python 在 IE 中使用 window.scroll 向下滚动页面对我不起作用