简体   繁体   English

如何在将列表与前一个元素进行比较时从列表中删除项目?

[英]How to remove items from a list while comparing it to the previous element?

I am trying to remove items from a list using a for loop in Python, if they are equal to the previous element in the list.我正在尝试使用 Python 中的 for 循环从列表中删除项目,如果它们等于列表中的前一个元素。

When I try to use del, I get a list index out of range error, which through research I have learned that it is because using del alters the length of my list.当我尝试使用 del 时,我得到一个列表索引超出范围错误,通过研究我了解到这是因为使用 del 改变了我的列表的长度。

Other advice has said to use list comprehension instead, but I'm unsure how to compare the previous element to the current element, while doing so.其他建议说要使用列表理解,但我不确定如何将前一个元素与当前元素进行比较,同时这样做。

This is my current code:这是我当前的代码:

for x in range(1, len(items)):
    if items[x] == items[x-1]:
        del items[x]
        del items[x - 1]
return result

Try this:尝试这个:

import pandas as pd


items = [1, 4, 4, 5, 5, 5, 6, 4, 5, 7]
remove_us = []

for x in range(1, len(items)):
    if items[x] == items[x - 1]:
        # save the index
        remove_us.append(x)

# create a Series out of your items
items_temp = pd.Series(items)
items_filtered = items_temp.drop(axis=1, index=remove_us).values
# With .values you get a numpy.ndarray
# If, for some reason, you need a list you can do:
# items_filtered = list(items_filtered)

result:结果:

array([1, 4, 5, 6, 4, 5, 7])数组([1, 4, 5, 6, 4, 5, 7])


The following is an approach, in case you want to remove dublicates in general:以下是一种方法,以防您一般要删除重复项:

import pandas as pd


items_temp = pd.Series(items)
items_filtered = items_temp[~items_temp.duplicated(keep=False).values

I tried to address your problem changing the mechanics only where necessary:我试图解决您的问题,仅在必要时更改机制:

def my_func(list):

    # copy input list for data-safety reasons
    result = list.copy()

    # empty list and 1-element list require special treatment
    if len(list)==0 or len(list)==1:
        return result

    # init current_index
    current_index = 0

    while(current_index < len(result)-1):

        # validation-check for testing purposes, comment or delete for final version
        print("at current_index: {}".format(current_index))
        print("analyzed list is: {}".format(result))
        print("analyzed list is of length: {}".format(len(result)))
        print("comparing: {} with {}".format(result[current_index], result[current_index+1]))

        if result[current_index] == result[current_index+1]:
            result.pop(current_index)
            # don't augment current_index
            current_index += 0

        else:
            # augment current_index
            current_index += 1

        print()

    return result

Tests:测试:

>>> my_func([])
[]

my_func(['a'])
['a']

>>> my_func(['a','a'])
at current_index: 0
analyzed list is: ['a', 'a']
analyzed list is of length: 2
comparing: a with a

['a']

>>> my_func(['a','a','a'])
at current_index: 0
analyzed list is: ['a', 'a', 'a']
analyzed list is of length: 3
comparing: a with a

at current_index: 0
analyzed list is: ['a', 'a']
analyzed list is of length: 2
comparing: a with a

['a']

>>> my_func(['a','b','b','c','b','c','c'])
at current_index: 0
analyzed list is: ['a', 'b', 'b', 'c', 'b', 'c', 'c']
analyzed list is of length: 7
comparing: a with b

at current_index: 1
analyzed list is: ['a', 'b', 'b', 'c', 'b', 'c', 'c']
analyzed list is of length: 7
comparing: b with b

at current_index: 1
analyzed list is: ['a', 'b', 'c', 'b', 'c', 'c']
analyzed list is of length: 6
comparing: b with c

at current_index: 2
analyzed list is: ['a', 'b', 'c', 'b', 'c', 'c']
analyzed list is of length: 6
comparing: c with b

at current_index: 3
analyzed list is: ['a', 'b', 'c', 'b', 'c', 'c']
analyzed list is of length: 6
comparing: b with c

at current_index: 4
analyzed list is: ['a', 'b', 'c', 'b', 'c', 'c']
analyzed list is of length: 6
comparing: c with c

['a', 'b', 'c', 'b', 'c']

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

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