[問題] countif in a list?

看板Python作者 ( )時間1年前 (2022/08/15 01:14), 編輯推噓7(708)
留言15則, 9人參與, 1年前最新討論串1/1
不好意思打擾大家 想請教一下 my_list = [0,1,2,3,4] 要怎麼樣算出裡面>2的元素有幾個 (兩個) 感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.192.240.229 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1660497292.A.043.html

08/15 01:59, 1年前 , 1F
sum(n>2 for n in my_list)
08/15 01:59, 1F

08/15 09:40, 1年前 , 2F
迴圈算
08/15 09:40, 2F

08/15 11:25, 1年前 , 3F
count = 0
08/15 11:25, 3F

08/15 11:25, 1年前 , 4F
for i in my_list:
08/15 11:25, 4F

08/15 11:25, 1年前 , 5F
if i > 2:
08/15 11:25, 5F

08/15 11:25, 1年前 , 6F
count += 1
08/15 11:25, 6F

08/15 11:25, 1年前 , 7F
return count
08/15 11:25, 7F

08/15 11:29, 1年前 , 8F
喔return那行多的,這不是函數
08/15 11:29, 8F

08/15 11:51, 1年前 , 9F
len([m for m in my_list if m > 2])
08/15 11:51, 9F

08/15 13:46, 1年前 , 10F
推樓上IAMPF的做法
08/15 13:46, 10F

08/15 14:46, 1年前 , 11F
IAMPF 的做法挺漂亮的
08/15 14:46, 11F

08/15 15:38, 1年前 , 12F
以效率來說還是1F比較好
08/15 15:38, 12F

08/15 17:05, 1年前 , 13F
sum(map((2.).__lt__, my_list))
08/15 17:05, 13F

08/15 17:05, 1年前 , 14F
啊和1F一樣意思
08/15 17:05, 14F

08/16 00:12, 1年前 , 15F
最Pythonic推IAMPF
08/16 00:12, 15F
文章代碼(AID): #1Y-IsC13 (Python)
文章代碼(AID): #1Y-IsC13 (Python)