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)
    
  • 相关阅读:
    自己写的一个后台模板
    php计算登陆时间差
    友盟推送,php简单代码
    rolling_curl curl批量采集函数留份
    PHP socket服务框架
    JS 画饼图,折线图
    jquery 日期插件
    JS 获取当前页面url,及锚点
    PHP 读取文件,返回二进制流
    各个数据库DataSource配置文件
  • 原文地址:https://www.cnblogs.com/BigShuang/p/15685716.html
Copyright © 2011-2022 走看看