【python解题笔记20210318】CodeWars:Delete occurrences of an element if it occurs more than n times

题目

内容:检测传入的列表,根据入参的重复次数,保留列表的元素。

链接:https://www.codewars.com/kata/554ca54ffa7d91b236000023/train/python

截图:

   

解题

思路: 

1、首先利用list.count(list[下标]),计算列表中每个元素的出现次数;

2、针对出现次数大于入参要求的重复次数时,删除该元素;

3、由于题目要求保留列表前面部分,删除后面出现的重复元素,因此利用for循环的倒序查找从列表的尾部检测;

4、利用del list[下标]来删除列表指定下标的元素。

结果:

   

源码:

def delete_nth(order,max_e):
    # code here
    a=order
    times=max_e
    for i in range(len(a) - 1,1,-1):
        if a.count(a[i]) > times:
            del a[i]
            print(a)
            pass
        else:
            pass
        pass
    return a

知识点

1、for i in range(10,1,-1),-1表示从大往小取值、1表示取值间隔、10表示最大值10。利用这样的方式,进行从大到小循环。

2、list.count(list[下标]),计算列表中每个元素的出现次数。

3、del list[下标]来删除列表指定下标的元素。

参考资料:

https://www.runoob.com/python/python-lists.html

https://blog.csdn.net/weixin_43678298/article/details/108123677

原文地址:https://www.cnblogs.com/chooperman/p/14554961.html