Python 篩選去除只有一次出現的數字
阿新 • • 發佈:2018-11-12
上一篇知道了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]
那要是我想生成一個特別大的列表,那肯定裝不下,這時候就有生成器這個概念,生成器
很厲害的用法,只有用到的時候才算出來,很省空間