2016-09-14 108 views
-1
string = "hello world i'm a new program" 
words_length = [] 
length = 21 

我使用re.split生產單詞和空間的列表:爲什麼列表刪除功能不會刪除空格?

words = re.split('\w', string) 

這樣:

words = ['hello', ' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 

for x in words: 
    words_length.append(len(x)) 

    for x in range(len(words)): 
     if words_length < length: 
     words_length += letters_length[x] 
     line += words[x]  
     del words[x] 

,但最後當我打印的變量,我得到:

line = "helloworldi'manew" 
words = [' ', ' ', ' ', ' ', ' ', 'program'] 

但我想要的是:

line = "hello world i'm a new" 
words = ['program'] 

我該如何設法做到這一點?

+0

您正在跳過索引。試着用[['','a','','b','']'來看看這與空間無關。 –

+0

另外,'letters_length'和'length'是什麼? –

+1

在遍歷它的時候修改一個序列通常是一個壞主意。 –

回答

3

您是跳過索引,因爲您正在從列表中刪除字符。

每次刪除一個角色時,該角色的權利的所有內容向左移動一步,其索引減少一個。但你的x指數仍然由一個上升所以現在你引用列表後面的元素:

x == 0 
words == ['hello', ' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 
#  0  1 2  3 4 5 ... 
words[x] == 'hello' 

del words[x] 
words == [' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 
#   0 1  2 3 4 5 ... 
  • 你的循環的第二次迭代:

    的for循環

    1. 第一次迭代

      x == 1 
      words == [' ', 'world', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 
      #   0 1  2 3 4 5 ... 
      words[x] == 'world' 
      
      del words[x] 
      words == [' ', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 
      #   0 1 2 3 4 5 ... 
      
    2. 你的循環的第三次迭代

      x == 2 
      words == [' ', ' ', 'i', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 
      #   0 1 2 3 4 5 ... 
      words[x] == 'i' 
      
      del words[x] 
      words == [' ', ' ', "'", 'm', ' ', 'a', ' ', 'new', ' ', 'program'] 
      #   0 1 2 3 4 5 ... 
      

    不要從你的列表中的條目,直到至少循環;你不需要讓他們在循環過程中刪除:

    line = [] 
    current_length = 0 
    for i, word in enumerate(words): 
        current_length += len(word) 
        if current_length > length: 
         i -= 1 
         break 
        line.append(word) 
    # here i is the index of the last element of words actually used 
    words = words[i + 1:] # remove the elements that were used. 
    line = ''.join(line) 
    

    ,或者你可以刪除的話(從效率的逆轉清單),但後來使用while環和用於測試的累計長度,而不是:

    line = [] 
    current_length = 0 
    reversed_words = words[::-1] 
    while reversed_words: 
        l = len(reversed_words[-1]) 
        if current_length + l > length: 
         break 
        line.append(reversed_words.pop()) 
        current_length += l 
    words = reversed_words[::-1] 
    line = ''.join(line) 
    

    但是,如果您嘗試將行長包裝應用於Python字符串,則可以使用textwrap module來避免重新發明該輪子。它可以輕鬆地在最大長度範圍內進行換行:

    wrapped = textwrap.fill(string, length)