zoukankan      html  css  js  c++  java
  • 大爽Python入门练习题 27 列表去重

    大爽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)
    
  • 相关阅读:
    第四节 pandas 数据加载
    第五节 matplotlib库
    第二节 pandas 基础知识
    第一节 anaconda+jupyter+numpy简单使用
    枚举效率测试 --简单计算题
    Tree 树形结构
    django url分发,视图,模板回顾
    django自定义分页器
    转git的使用
    转Git配置SSH,并Push到GitHub上的相关流程
  • 原文地址:https://www.cnblogs.com/BigShuang/p/15685716.html
Copyright © 2011-2022 走看看