【问题标题】:Deleting one position to another position elements from list in python从python中的列表中删除一个位置到另一个位置元素
【发布时间】:2018-02-14 12:01:32
【问题描述】:

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

【问题讨论】:

  • 你能贴出你目前尝试过的代码吗?
  • 太棒了!祝你好运!如果您遇到困难,请就您尝试和研究过的内容提出问题。阅读How to Ask了解更多指南
  • bool_digit = True indexOfZero = 0 indexOfWord = 0 for key in array: if key.isdigit(): print(key) else: indexOfWord = array.index(key) bool_digit = False if key == "0": indexOfZero = array.index(key) if indexOfZero > indexOfWord: bool_digit = True while bool_digit: print(key) bool_digit = False
  • 请通过放置您目前拥有的代码来编辑您的问题,并且不要在评论部分发布它。
  • @kamcode 通过包含您尝试过的代码 sn-p 来编辑您的问题

标签: python arrays list elements


【解决方案1】:

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

【讨论】:

  • 是不是像这样的“Skip-True”这样的词不能这样做......我的意思是 isalpha 只需要词。如果有任何字符应该发生上述过程。
【解决方案2】:
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']

【讨论】:

    【解决方案3】:

    踢它老派 -

    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)
    

    【讨论】:

    • 在索引中给出“0”不是正确的方法。如果 array[i:] 不包含 '0' 值,它将中断。
    猜你喜欢
    • 2017-10-19
    • 2022-11-13
    • 2013-06-28
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多