python:如何从列表中选择特定值

时间:2016-08-25 04:33:26

标签: python-2.7

我是python的新手,在尝试了很多之后,我无法找到解决以下问题的方法。

我有列表(下面)并希望找到元素的索引号,前提是它们是连续的,除了1个单个零。 即,从下面的列表中<?php $counter=0;?> @foreach ($sales as $salesperson => $name) {!! Form::hidden('employee_id['.$counter.']',0 ) !!} {!! Form::checkbox('employee_id['.$counter.']',$salesperson ) !!} {!! $name !!} <br/> *Alasan Jika Tidak Masuk: {!! Form::text('employee_reason['.$counter.']','',['class' => 'form-control','id'=>'employee_id-field'] ) !!} <br/> <?php $counter = $counter+1; ?> @endforeach 不应该被选中,因为它们之间存在更多的零间隙。 但是应该选择以下索引数量的元素

-7, -8, -4

请帮忙。

1 个答案:

答案 0 :(得分:0)

    deltacount = [0,-7, 0, 0,-8, 0, 0,-4, 0,0,0,-6,0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 0]
zero_before_count=0
zer_after_count=0
indx=0
list1=[]
for i in deltacount:
    if i!=0:
        indx=deltacount.index(i)
        if deltacount[indx-1]==0 and deltacount[indx-2]==0:
            if deltacount[indx+1]==0 and deltacount[indx+2]==0:
                list1.append(i)
finallist=[x for x in deltacount if x not in list1 and x!=0]
print finallist

试试这段代码。