如何索引,删除和计算列表中元素的所有实例?

时间:2019-01-28 14:41:06

标签: python python-3.x list function

我是Python的新手,我正在尝试学习有关列表的知识。在这种情况下,我的目标是对列表中某个元素的所有实例进行索引,计数和删除。索引,计数和删除所有功能都可以单独正常工作,但是我正在努力将其合并并获得所需的结果。我在做什么错了?

def removing(letter,lst):
    '''This function should index and remove all entries of a letter within a list, returning the removed items' position within the original list. I then use len() function on the result-list to determine how many items have been indexed/deleted'''
    result=[]
    offset= -1
    list_new = lst.copy()
    while True:
        try:
            offset=list_new.index(letter, offset+1)
        except ValueError:
            return result
            print('Letter not found.')
        result.append(offset)
        lst.remove(letter)

现在,我希望即使不克隆列表也能解决问题,该函数返回字母的位置并删除它们,但是当我定义lstletter时,运行该函数然后说:

print(len(removing(letter,lst)))

总是说0。为什么呢?

编辑:建议我一次调用该函数并存储结果,但是当我执行以下操作时,结果是相同的:

c=1
print(lst)
while (c==1):
    letter=input('What letter do you want to remove?\n')
    if letter in lst:
        var=removing(letter,lst)
        print(var)
        print(str(len(var))+' letters have been removed.')
        print(lst)
    else:
        c-1

3 个答案:

答案 0 :(得分:0)

您的循环不是必需的,并且将无限循环。试试下面的

lst = list('abracadabra')
letter = 'a'

var=removing(letter,lst)
print(var)  # [0, 3, 5, 7, 10]
print(str(len(var))+' letters have been removed.')  # 5 letters have been removed.
print(lst)  # ['b', 'r', 'c', 'd', 'b', 'r']

另一种以更Python化的方式编写函数的方法将是

def remove(lst, item):
    new_list = []
    indices = []
    for i, x in enumerate(lst):
        if x == item:
            indices.append(i)
        else:
            new_list.append(x)
    return new_list, indices

答案 1 :(得分:0)

谢谢大家的帮助,我的问题已经回答。问题不在函数中,而是我多次调用函数而不存储结果。最终代码如下:

    lst= list('Nach langem rumprobieren haben nette Menschen mir bei der Vollendung dieser kleinen Übungsaufgabe geholfen.')

    def removing(letter,lst):
        'This function should remove all entries of a letter within a list'
    result=[]
    offset= -1
    list_new = lst.copy()
    while True:
        try:
            offset=list_new.index(letter, offset+1)
        except ValueError:
            return result
        result.append(offset)
        lst.remove(letter)

    c=1
    print(lst)
    while (c==1):
        letter=input('What letter do you want to remove?\n')
        if letter in lst:
            var=removing(letter,lst)
            print(var)
            print(str(len(var))+' letters have been removed.')
            print(lst)
        else:
            break

答案 2 :(得分:0)

这是我的解决方法:

import re

def removing(c, s):
    '''This function removes all occurences of 'c' in 's' and return a list of the replaced indices'''
    indices = [i.span()[0] for i in re.finditer(c, s)]
    return s.replace(c, ''), indices

这是用法示例:

>>> removing('a', 'abracadabra')
('brcdbr', [0, 3, 5, 7, 10])
>>> 
>>> removing('a', 'aaaaa')
('', [0, 1, 2, 3, 4])
>>>