2017-08-21 148 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