gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:24:11 25 4
gpt4 key购买 nike

列表包含全名和简称。我想将以下列表中的短名称扩展为其全名。例如。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com