我有一组名字:
>>> name_set = {'A.C. Johnson',
'Adrian Jefferson',
'Albus Jung',
'Al Frank',
'Alex English',
'Allen Peters'}
>>> type(name_set)
set
部分名称需要调整。例如,我需要:
name_set = {'A.C. Johnson15',
'Adrian Jefferson',
'Albus Jung',
'Al Frank',
'Alex English40',
'Allen Peters35'}
我已经尝试过:
name_set.remove("A.C. Johnson")
name_set.add("A.C. Johnson15")
我试图避免重复这个^所以
我也尝试过:
fixed_name_set = [name.replace('A.C. Johnson', 'A.C. Johnson15') for name in name_set]
这^是一行,但仍然需要重复来替换多个名称。所以我尝试过类似的方法:
fixed_name_set = [name.replace(('A.C. Johnson', 'A.C. Johnson15'), ('Alex English', 'Alex English40')) for name in combined_top_players]
与此类似的解决方案^将是理想的选择,但会产生TypeError: Can't conversion 'tuple' object to strimplicitly
用另一个值替换多个唯一字符串的 pythonic 解决方案是什么?
最佳答案
您可以使用difference和 union set
操作一次删除/添加多个集合元素,例如:
>>> name_set = {'A.C. Johnson15', 'Adrian Jefferson', 'Albus Jung', 'Al Frank', 'Alex English40', 'Allen Peters35'}
>>> name_set - {'A.C. Johnson', 'Alex English'} | {'A.C. Johnson15', 'Alex English40'}
{'Albus Jung', 'A.C. Johnson15', 'Allen Peters35', 'Al Frank', 'Adrian Jefferson', 'Alex English40'}
或者使用设置方法:
>>> name_set.difference(['A.C. Johnson', 'Alex English']).union(['A.C. Johnson15', 'Alex English40'])
{'Albus Jung', 'A.C. Johnson15', 'Allen Peters35', 'Al Frank', 'Adrian Jefferson', 'Alex English40'}
关于python - 一次将集合中的多个唯一字符串项替换为多个其他字符串项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46422262/