繁体   English   中英

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

[英]Deleting one position to another position elements from list in python

我有一个如下所示的列表,我想删除任何单词(包括)和下一个'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']
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']

踢它老派-

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)

您也可以通过专门使用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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM