删除相邻的重复元素后打印列表

时间:2017-11-15 17:51:13

标签: python recursion

new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list

问题:给定一个数字列表,返回一个列表,其中所有相邻的==元素已减少为单个元素,因此[1, 2, 2, 3]返回[1, 2, 3]。您可以创建新列表或修改传入列表。

问题:打印的最终列表包含[1, 2, 3, 5]而不是[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

4 个答案:

答案 0 :(得分:3)

您想要的是itertools.groupby

最佳解决的问题
l
Out[35]: [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

from itertools import groupby
[k for k, _ in groupby(l)]
Out[36]: [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

itertools.groupby的作用是,它通过生成元素的元组和连续的组作为列表将连续的键组合在一起

为了清楚地了解itertools.groupby,您可以转储通过对连续数字列表进行分组而生成的元组结果列表

[(k, list(g)) for k, g in groupby(l)]
Out[40]: 
[(1, [1]),
 (2, [2]),
 (3, [3]),
 (5, [5]),
 (4, [4, 4]),
 (5, [5, 5]),
 (6, [6]),
 (7, [7, 7, 7]),
 (8, [8, 8]),
 (9, [9]),
 (8, [8, 8])]

答案 1 :(得分:1)

new_list = []

def remove_adjacent(nums):
    i = 0
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
        i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

# appending the last item
new_list.append(l[len(l)-1])

print (new_list.append(nums[len(nums) - 1]))

输出

[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

答案 2 :(得分:1)

这对于发电机来说是完美的。我没有改变原来的名单。相反,我正在返回一个没有相邻值的新列表。

def removerator(l):
    last = None
    for x in l:
        if x != last:
            last = x
            yield x

list(removerator(l))

[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

设置

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

答案 3 :(得分:-1)

我创建了一个函数,它获取一个列表并迭代它的项目,然后它添加的项目与上一次迭代中已经添加到列表中的项目相同。

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]  # List that we want to change

def remove_adjacent(l):             # Define a new function and accept an argument: the list to check.
    new = [l[0]]                    # Make a new list (temporal) and assing like it's first item the first item of the main list. It's the same as new = [] and new.append(l[0]).
    for item in l[1:]:              # We iterate across the list, but we don't iterate on the first item because we've alreaday added it to the list, if you want you can delete the slice in [1:] since it will only make the iteration a really small fraction more slowly.
        if new[-1] != item:         # We check if the new item is the same as the last item added to the new list, if not, we add it.
            new.append(item)        # We add the item to the new list.
    return new                      # We return the list.

print(remove_adjacent(l))           # We check it.
# [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]