代码之家  ›  专栏  ›  技术社区  ›  Nick Bohl

是否用“x”替换列表中的重复值?

  •  0
  • Nick Bohl  · 技术社区  · 6 年前

    我试图理解创建一个函数的过程,该函数可以替换字符串列表中的重复字符串。例如,我想转换这个列表

    mylist = ['a', 'b', 'b', 'a', 'c', 'a']
    

    为了这个

    mylist = ['a', 'b', 'x', 'x', 'c', 'x']
    

    最初,我知道我需要创建函数并遍历列表

    def replace(foo):
        newlist= []
        for i in foo:
            if foo[i] == foo[i+1]:
                foo[i].replace('x')
        return foo
    

    list indices must be integers or slices, not str
    

    所以我认为我应该在这个列表的范围内操作,但我不确定如何实现它。另一种说法是,这只会帮助我,如果重复的信直接在我的迭代(i)之后。

    不幸的是,这是我对这个问题的理解。如果有人能为我澄清一下这个程序,我将非常感激。

    4 回复  |  直到 6 年前
        1
  •  2
  •   Ben    6 年前

    浏览列表,记录下你在一组中看到的东西。用“x”替换列表中以前看到的内容:

    mylist = ['a', 'b', 'b', 'a', 'c', 'a']
    
    seen = set()
    for i, e in enumerate(mylist):
        if e in seen:
            mylist[i] = 'x'
        else:
            seen.add(e)
    
    print(mylist)
    # ['a', 'b', 'x', 'x', 'c', 'x']
    
        2
  •  1
  •   Adnan Mohib    6 年前

    简单的解决方案。

    my_list = ['a', 'b', 'b', 'a', 'c', 'a']
    new_list = []
    
    for i in range(len(my_list)):
        if my_list[i] in new_list:
            new_list.append('x')
        else:
            new_list.append(my_list[i])
    print(my_list)
    print(new_list)
    
    # output
    #['a', 'b', 'b', 'a', 'c', 'a']
    #['a', 'b', 'x', 'x', 'c', 'x']
    
        3
  •  0
  •   Adam    6 年前

    其他的解决方案使用索引,这并不一定是必需的。

    很简单,你可以检查一下 if in 新名单, else 你可以 append x、 如果要使用函数:

    old = ['a', 'b', 'b', 'a', 'c']
    
    def replace_dupes_with_x(l):
        tmp = list()
        for char in l:
            if char in tmp:
                tmp.append('x')
            else:
                tmp.append(char)
    
        return tmp
    
    new = replace_dupes_with_x(old)
    
        4
  •  -1
  •   Noam Peled    6 年前

    您可以使用以下解决方案:

    from collections import defaultdict
    
    mylist = ['a', 'b', 'b', 'a', 'c', 'a']
    ret, appear = [], defaultdict(int)
    for c in mylist:
         appear[c] += 1
         ret.append(c if appear[c] == 1 else 'x')
    

    它会给你:

    ['a'、'b'、'x'、'x'、'c'、'x']

    推荐文章