将列表中的0之间的零替换为零

时间:2017-06-24 20:58:31

标签: python list slice

假设我有一个如下所示的列表。你怎么能遍历列表并替换之间的零之间的零点,其间的零长度可以变化?

输入:

mylist = [0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0]

输出:

mylist = [0,0,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0]

2 个答案:

答案 0 :(得分:4)

我认为你可以分两个阶段做到这一点:

  1. 首先我们获得指示的指数;和
  2. 我们一次拿两个,然后用一个填充。
  3. 像:

    import pandas as pd
    data = pd.read_excel('D:Downloads/titanic3.xls')
    
    data.head()
    Out[7]: 
       pclass  survived                                             name     sex  \
    0       1         1                    Allen, Miss. Elisabeth Walton  female   
    1       1         1                   Allison, Master. Hudson Trevor    male   
    2       1         0                     Allison, Miss. Helen Loraine  female   
    3       1         0             Allison, Mr. Hudson Joshua Creighton    male   
    4       1         0  Allison, Mrs. Hudson J C (Bessie Waldo Daniels)  female   
    
           age  sibsp  parch  ticket      fare    cabin embarked boat   body  \
    0  29.0000      0      0   24160  211.3375       B5        S    2    NaN   
    1   0.9167      1      2  113781  151.5500  C22 C26        S   11    NaN   
    2   2.0000      1      2  113781  151.5500  C22 C26        S  NaN    NaN   
    3  30.0000      1      2  113781  151.5500  C22 C26        S  NaN  135.0   
    4  25.0000      1      2  113781  151.5500  C22 C26        S  NaN    NaN   
    
                             home.dest  
    0                     St Louis, MO  
    1  Montreal, PQ / Chesterville, ON  
    2  Montreal, PQ / Chesterville, ON  
    3  Montreal, PQ / Chesterville, ON  
    4  Montreal, PQ / Chesterville, ON 
    

    这会产生:

    # obtain an iterable of the indices of the ones
    ones = iter([i for i,x in enumerate(mylist) if x == 1])
    
    # for every pair of indices
    for i0,i1 in zip(ones,ones):
        # iterate over the range
        for j in range(i0+1,i1):
            # and assign 1 to these indices
            mylist[j] = 1
    

答案 1 :(得分:0)

保持旗帜,无论你在哪里"内部" 1-1块(你需要更新0到1)或不。

这假设,单个(" last")1将生成一个直到列表末尾:

inside = False
for x in range(len(data)):
  if data[x]:
    inside = not inside
  elif inside:
    data[x] = 1
[ 0, 1, 0, 1, 0 ] -> [ 0, 1, 1, 1, 0 ]
[ 0, 1, 0, 0, 0 ] -> [ 0, 1, 1, 1, 1 ]

如果不是你想要的,那么最后1应该被忽略:

start_block = None
for x in range(len(data)):
  if data[x]:
    if start_block is not None:
      for y in range(start_block + 1, x):
        data[y] = 1
      start_block
    else: 
      start_block = x
[ 0, 1, 0, 1, 0 ] -> [ 0, 1, 1, 1, 0 ]
[ 0, 1, 0, 0, 0 ] -> [ 0, 1, 0, 0, 0 ]