上一篇知道了count,即可遍历出出现次数大于一就好了
上代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27def 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")
外国大神这样写
复制代码
1
2return [i for i in data if data.count(i) > 1]
用了一个列表生成器
复制代码
1
2
3
4
5
6def haha: #输出从一到十一平方的列表,for 和 in 不难理解 [x * x for x in range(1, 11)] #后面也能你弄个 if 判断条件语句 [x * x for x in range(1, 11) if x % 2 == 0]
那要是我想生成一个特别大的列表,那肯定装不下,这时候就有生成器这个概念,生成器
很厉害的用法,只有用到的时候才算出来,很省空间
最后
以上就是默默音响最近收集整理的关于Python 筛选去除只有一次出现的数字的全部内容,更多相关Python内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复