【问题标题】:Replace multiple unique string items in a set with multiple other string items at once一次将集合中的多个唯一字符串项替换为多个其他字符串项
【发布时间】:2017-09-26 09:09:40
【问题描述】:

我有一组名字:

>>> 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 convert 'tuple' object to str implicitly
用另一个值替换多个唯一字符串的pythonic解决方案是什么?

【问题讨论】:

    标签: python python-3.x list set


    【解决方案1】:

    您可以使用differenceunion 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'}
    

    或者使用set方法:

    >>> 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'}
    

    【讨论】:

      【解决方案2】:

      这里是使用pythonset comprehension的可读方式:

      >>> to_fix = { 'A.C. Johnson': 'A.C. Johnson15', 
      ...            'Alex English': 'Alex English40' }
      >>> name_set = {'A.C. Johnson',
      ...  'Adrian Jefferson',
      ...  'Albus Jung',
      ...  'Al Frank',
      ...  'Alex English',
      ...  'Allen Peters'}
      >>> new_nameset = { to_fix.get( x,x ) for x in name_set }
      

      此时,new_nameset 包含:

      {'Adrian Jefferson', 
      'Allen Peters', 
      'Al Frank', 
      'Albus Jung', 
      'Alex English40', 
      'A.C. Johnson15'}
      

      【讨论】:

        猜你喜欢
        • 2013-03-14
        • 2020-04-01
        • 2011-07-01
        • 1970-01-01
        • 2011-12-01
        相关资源
        最近更新 更多