大爽Python入门练习题 2-7 列表去重

2021/12/14 1:17:31

本文主要是介绍大爽Python入门练习题 2-7 列表去重,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

大爽Python入门练习题总目录

第二章 中期练习题 中等 第7题

题目

简介

实现一个函数clear_duplication(lst)
接受一个数组(列表)lst作为参数。
直接操作该数组,去除所有数值重复的项。
无返回值(因为改动直接在lst上生效了)

提醒

列表直接删除一项,一般推荐使用:
list.pop(index=-1)方法,
移除并返回指定索引index的项,index默认值为-1(此时删除最后一项)。

pop方法使用示例

示例出自本教程第二章 第三节 第三部分 列表方法 常用

>>> nums = [9, 12, 10, 12, 15]
>>> nums.pop()
15
>>> nums
[9, 12, 10, 12]
>>> nums.pop(2)
10
>>> nums
[9, 12, 12]

示例

示例一

lst = [1, 2, 3, 2, 1]
clear_duplication(lst)
print(lst)

输出为

[1, 2, 3]

示例二

lst = [8, 3, 2, 5, 1, 1, 3, 6, 1, 9, 2, 1]
clear_duplication(lst)
print(lst)

输出为

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

分割线

本小段没有实际意义,
仅用于分隔题目和答案。
防止学生无意中直接看到答案,
影响思路。



















答案

def clear_duplication(lst):
    clear_indexes = []
    record = []
    for index in range(len(lst)):
        item = lst[index]
        if item in record:
            clear_indexes.append(index)
        else:
            record.append(item)

    for index in clear_indexes[::-1]:  # 注意,要从后往前删除
        lst.pop(index)


这篇关于大爽Python入门练习题 2-7 列表去重的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程