2014-11-24 63 views
1

我使用Python 2.7.5,我有一個列表看起來像這樣:查找和替換列表中的空行寬的Python

('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '') 

名單是千瘡百孔,我想找出空行和用下一個非空行填充數據。如果有一個包含數據我想設置那些爲0。像這種沒有下一行:

('2047', '1971', '1919', '1919', '1878', '1878', '1760', '1760', '1760', '1731', '1667', '1667','0','0') 

我怎樣才能做到這一點與Python?我可以做一個簡單的循環來識別空行,但我不知道如何填補空白... 任何幫助將不勝感激! 謝謝 馬丁

+1

這不是一個列表,但一個元組。你的意思是[]而不是()? – 2014-11-24 08:46:50

+0

對不起,它是一個元組。我用zip(*數據)調換了數據並得到了一個元組返回 – 2014-11-24 08:52:17

回答

1

很容易記錄一個循環中的前一個值比未來的值。所以我的想法是扭轉名單。用前一個空值替換。最後將列表反轉回來,你會得到結果。

>>> lst=('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '') 
>>> lst=list(lst[::-1]) 
>>> pr=0 
>>> for j in range(len(lst)): 
...  if lst[j]=='': 
...  lst[j]=pr 
...  else: 
...  pr=lst[j] 
... 
>>> lst=lst[::-1] 
>>> lst 
['2047', '1971', '1919', '1919', '1878', '1878', '1760', '1760', '1760', '1731', '1667', '1667', 0, 0] 
+0

我喜歡這個論壇,謝謝! – 2014-11-24 09:01:15

+0

不客氣... – 2014-11-24 09:02:10

1
yourList = ['2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', ''] 

lastVal = '0' 
for i in range(len(yourList) -1, 0, -1): 
    if len(yourList[i])==0: 
    yourList[i ]= lastVal 
    else: 
    lastVal = yourList[i] 

print yourList 
+0

相當於BHAT IRSHAD的答案,只是它使尾隨零字符串。 – TheBigH 2014-11-24 09:04:54

3

您可以使用itertools.groupby此:

>>> from itertools import groupby 
>>> t = ('2047', '1971', '', '1919', '', '1878', '', '', '1760', '1731', '', '1667', '', '') 
>>> out = [] 
>>> prev = None 
for k, g in groupby(reversed(t)): 
    if k == '' and prev is None: 
     out.extend('0' for _ in g) 
    elif k == '' and prev is not None: 
     out.extend(prev for _ in g) 
    else: 
     for x in g: 
      out.append(x) 
     prev = x 
...    
>>> out.reverse() 
>>> out 
['2047', '1971', '1919', '1919', '1878', '1878', '1760', '1760', '1760', '1731', '1667', '1667', '0', '0']