在列表宽度Python中查找并替换空行

时间:2014-11-24 08:45:57

标签: python list loops

我使用的是Python 2.7.5,我有一个如下所示的列表:

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

列表中有很多漏洞,我想识别空行并用下一个非空行填充数据。如果没有包含数据的下一行,我想将它们设置为0.像这样:

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

我怎样才能用Python做到这一点?我可以做一个简单的for循环来识别空行,但我不知道如何填补空白...... 任何帮助将非常感激! 谢谢 马丁

3 个答案:

答案 0 :(得分: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']

答案 1 :(得分: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]

答案 2 :(得分: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