Python 筛选去除只有一次出现的数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010095372/article/details/79303396

上一篇知道了count,即可遍历出出现次数大于一就好了

上代码

def checkio(data):
    #Your code here
    #It's main function. Don't remove this function
    #It's used for auto-testing and must return a result for check.  
    #replace this for solution
    s = []
    #遍历
    for i in data:
        #筛选条件
        if data.count(i) > 1:
            s.append(i)
    return s

#Some hints
#You can use list.count(element) method for counting.
#Create new list with non-unique elements
#Loop over original list


if __name__ == "__main__":
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example"
    assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example"
    assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example"
    assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example"
    print("It is all good. Let's check it now")

外国大神这样写

 return [i for i in data if data.count(i) > 1]

用了一个列表生成器

def haha:
    #输出从一到十一平方的列表,for 和 in 不难理解
    [x * x for x in range(1, 11)]
    #后面也能你弄个 if 判断条件语句
    [x * x for x in range(1, 11) if x % 2 == 0]

那要是我想生成一个特别大的列表,那肯定装不下,这时候就有生成器这个概念,生成器
很厉害的用法,只有用到的时候才算出来,很省空间

猜你喜欢

转载自blog.csdn.net/u010095372/article/details/79303396