簡體   English   中英

如何在將列表與前一個元素進行比較時從列表中刪除項目?

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

我正在嘗試使用 Python 中的 for 循環從列表中刪除項目,如果它們等於列表中的前一個元素。

當我嘗試使用 del 時,我得到一個列表索引超出范圍錯誤,通過研究我了解到這是因為使用 del 改變了我的列表的長度。

其他建議說要使用列表理解,但我不確定如何將前一個元素與當前元素進行比較,同時這樣做。

這是我當前的代碼:

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

嘗試這個:

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)

結果:

數組([1, 4, 5, 6, 4, 5, 7])


以下是一種方法,以防您一般要刪除重復項:

import pandas as pd


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

我試圖解決您的問題,僅在必要時更改機制:

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

測試:

>>> 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