【问题标题】:Get unique elements (elements that don't repeat next to each other) from a sequence从序列中获取唯一元素(彼此不重复的元素)
【发布时间】:2021-06-02 18:23:40
【问题描述】:

我正在尝试编写一个 func(),它只返回来自给定输入的唯一元素,以相同的顺序。

例如 - 'AAAABBBCCDAABBB' 将返回 ['A', 'B', 'C', 'D', 'A', 'B']

只是一个初学者,所以如果我能得到一些帮助会很棒。 在下面附上我的代码 - 如果在可读性方面不是最佳实践,我们深表歉意。

enter code here 
def unique_in_order(string):

new_list =[]


#using a for loop access the elements 
for n in range(len(string)):
    
    print(string[n],string[n+1])
    
    if string[n] != string[n+1]:
        new_list.append(string[n])
        
return new_list

我得到的输出

【问题讨论】:

    标签: python list function for-loop indexing


    【解决方案1】:

    当检查字符串的最后一个元素时,您访问的元素 n+1 超出了字符串的范围。更正后的代码如下所示:

    def unique_in_order(string):
        if len(string) == 0:
            return [];
        new_list = [string[0]]
        #using a for loop access the elements 
        for n in range(1, len(string)):        
            print(string[n-1],string[n])
            if string[n] != string[n-1]:
                new_list.append(string[n])
        return new_list
    

    【讨论】:

      【解决方案2】:

      在python中你可以使用groupby方法来做到这一点

      from itertools import groupby
      
      my_str = "AAAABBBCCDAABBB"
      res = list(map(lambda x: x[0], groupby(my_str)))
      
      print(res) # ['A', 'B', 'C', 'D', 'A', 'B']
      

      【讨论】:

        【解决方案3】:

        您在最后一个循环中遇到索引错误。由于您正在检查string[n+1] 在最后一个循环中,当您执行 n+1 时,它将超出索引。

        【讨论】:

        • 是的,我理解错误,但只是没有尝试做 n-1 !再次感谢
        【解决方案4】:

        这可能是一种方法。这会查看之前的项目而不是前面的项目,因此您不会收到您遇到的错误。

        def unique_in_order(string):
            new_list = []
            for i in range(len(string)):
                # if the new letter isn't same as previous then add to list
                if string[i] != string[i - 1]: 
                     new_list.append(string[i])
                else:
                     pass
            return new_list `
        

        【讨论】:

          【解决方案5】:

          正则表达式?

          >>> re.findall(r'(.)\1*', 'AAAABBBCCDAABBB')
          ['A', 'B', 'C', 'D', 'A', 'B']
          

          【讨论】:

            猜你喜欢
            • 2020-04-30
            • 2013-08-14
            • 1970-01-01
            • 1970-01-01
            • 2018-01-17
            • 2017-12-08
            • 2011-11-14
            • 2018-09-09
            • 1970-01-01
            相关资源
            最近更新 更多