从python中的列表中删除一个位置到另一个位置元素

时间:2018-02-14 12:01:33

标签: python arrays list elements

我有一个如下所示的列表,我想删除 任何单词(包括)和下一个'0'之间的所有条目(独占)。

例如这个列表:

array = ['1', '1', '0', '3', '0', '2', 'Continue', '1', '5', '1', '4', '0', '7', 'test', '3', '6', '0']

应该成为:

['1', '1', '0', '3', '0', '2', '0', '7', '0']

3 个答案:

答案 0 :(得分:0)

array = ['1', '1', '0', '3', '0', '2', 'Continue', '1', '5', '1', '4', '0', '7', 'test', '3', '6', '0']

res = []
skip = False      #Flag to skip elements after a word
for i in array:
    if not skip:
        if i.isalpha():   #Check if element is alpha
            skip = True
            continue
        else:
            res.append(i)
    else:
        if i.isdigit():   #Check if element is digit
            if i == '0':
                res.append(i)
                skip = False

print res

<强>输出:

['1', '1', '0', '3', '0', '2', '0', '7', '0']

答案 1 :(得分:0)

踢它老派 -

array = ['1', '1', '0', '3', '0', '2', 'Continue', '1', '5', '1', '4', '0', '7', 'test', '3', '6', '0']
print(array)
array_op = []
i=0
while i < len(array):
    if not array[i].isdigit():
        i = array[i:].index('0')+i
        continue
    array_op.append(array[i])
    i += 1
print(array_op)

答案 2 :(得分:0)

您也可以专门使用list comprehension

array = ['1', '1', '0', '3', '0', '2', 'Continue', '1', '5', '1', '4', '0', '7', 'test', '3', '6', '0']

# Find indices of strings in list
alphaIndex = [i for i in range(len(array)) if any(k.isalpha() for k in array[i])] 

# Find indices of first zero following each string
zeroIndex = [array.index('0',i) for i in alphaIndex] 

# Create a list with indices to be `blacklisted`
zippedIndex = [k for i,j in zip(alphaIndex, zeroIndex) for k in range(i,j)] 

# Filter the original list
array = [i for j,i in enumerate(array) if j not in zippedIndex] 

print(array)

输出:

['1', '1', '0', '3', '0', '2', '0', '7', '0']