2017-08-21 147 views
0

我实际上需要帮助来评估我写的代码正在发生什么。Python 3.xx - 从字符串中删除连续的数字/字母

这意味着这样的功能:

input: remove_duple('WubbaLubbaDubDub') 

output: 'WubaLubaDubDub' 

另一个例子:

input: remove_duple('aabbccdd') 

output: 'abcd' 

我还是一个初学者,我想知道这两个有什么错我的代码和更容易方法来做到这一点。 (有些情况下,是我努力想象发生了什么事的一部分,调试它的一些代码行)

def remove_duple(string): 
    to_test = list(string) 
    print (to_test) 
    icount = 0 
    dcount = icount + 1 
    for char in to_test: 
     if to_test[icount] == to_test[dcount]: 
      del to_test[dcount] 
      print ('duplicate deleted') 
      print (to_test) 
      icount += 1 
     elif to_test[icount] != to_test[dcount]: 
      print ('no duplicated deleted') 
      print (to_test) 
      icount += 1 
    print ("".join(to_test)) 
+0

看看它看起来有多简单[用正则表达式](https://ideone.com/BpT3NE)。 –

回答

0

不要修改list(例如del to_test[dcount])您遍历。你的迭代器会搞砸。处理这个问题的适当方法是创建一个新的list,只有你想要的值。

用于您的代码修复可能看起来像:

In []: 
def remove_duple(s): 
    new_list = [] 
    for i in range(len(s)-1): # one less than length to avoid IndexError 
     if s[i] != s[i+1]: 
      new_list.append(s[i]) 
    if s:      # handle passing in an empty string 
     new_list.append(s[-1]) # need to add the last character 

    return "".join(new_list) # return it (print it outside the function) 

remove_duple('WubbaLubbaDubDub') 

Out[]: 
WubaLubaDubDub 

当你正在寻找步骤通过串,每次滑动2个字符,你可以做到这一点只需zip荷兰国际集团与自身的串移一个,并添加第一个字符,如果2个字符不相等,比如:

In []: 
import itertools as it 

def remove_duple(s): 
    return ''.join(x for x, y in it.zip_longest(s, s[1:]) if x != y) 

remove_duple('WubbaLubbaDubDub') 

Out[]: 
'WubaLubaDubDub' 

In []: 
remove_duple('aabbccdd') 

Out[]: 
'abcd' 

注意:您需要itertools.zip_longest()或者你会下降的最后一个字符。 None的默认fillvalue适用于字符串。

+0

感谢您的快速回复。我需要澄清一下你给出的第一个代码: 'if s:new_list.append(s [-1])' 你评论说它是用于处理空字符串是否通过,但我尝试过放置空格并给出没有这行代码的空字符串和输出是相同的。这条线究竟做了什么? –

+0

如果你没有这行,并传递一个空字符串''''你会得到一个'IndexError'。 – AChampion