關(guān)于python統(tǒng)計(jì)一個(gè)整數(shù)列表中不同數(shù)值種類數(shù)的問(wèn)題。
問(wèn)題描述
下面這段代碼中,kind_num用于統(tǒng)計(jì)那個(gè)整數(shù)列表中有幾種不同數(shù)值的整數(shù)。
class Solution(object): def distributeCandies(self, candies):''':type candies: List[int]:rtype: int'''loc = len(candies)mol = loc % 2if not (2 <= loc <= 10000) or mol != 0: return ’wrong length of array’for num in candies: if not (-10000 <= num <= 10000):return ’wrong element in array’kind_num = 0sis_num = loc / 2for candy in candies: kind_num += 1 while True:try: candies.remove(candy) print candiesexcept ValueError: breakif kind_num > sis_num: return sis_numelif kind_num < sis_num: return kind_numelse: return sis_nums = Solution()print s.distributeCandies([1,1,2,2,3,3])
但是第二個(gè)for循環(huán),沒有取完candies里面的值就提前退出了,這是為什么???
問(wèn)題解答
回答1:在循環(huán)里不要去remove
如果你僅僅是想實(shí)現(xiàn)統(tǒng)計(jì)不同種類的值
#統(tǒng)計(jì)出現(xiàn)次數(shù)lst = [1,1,2,2,3,3,4,4,5,6]print len(set(lst))#統(tǒng)計(jì)每種各出現(xiàn)幾次from collections import Counterprint dict(Counter(lst))回答2:
candies.remove(candy) 第一次執(zhí)行 Ok, candy被remove; 由于while (True), 在同一次For 循環(huán)中 會(huì)無(wú)限r(nóng)emove 這個(gè)candy,但是這個(gè)candy 已經(jīng)在第一次被移除了。所以break.
回答3:from collections import defaultdictd = defaultdict(int)for item in your_list: d[item] += 1 print d
相關(guān)文章:
1. 輸入地址報(bào)以下截圖錯(cuò)誤,怎么辦?2. python中return 語(yǔ)句與 分支語(yǔ)句連用問(wèn)題3. thinkphp3 count()方法必須加上字段?4. python - 這句是什么錯(cuò)誤?5. 這是什么情況???6. mysql 5個(gè)left關(guān)鍵 然后再用搜索條件 幾千條數(shù)據(jù)就會(huì)卡,如何解決呢7. node.js - nodejs中mysql子查詢返回多行結(jié)果怎么處理?8. 怎么php怎么通過(guò)數(shù)組顯示sql查詢結(jié)果呢,查詢結(jié)果有多條,如圖。我要forsearch里面echo9. mysql - SQL server 誤用delete 怎么恢復(fù)?10. mysql - 瞬間流量很高的網(wǎng)站,要頻繁的插入數(shù)據(jù)到數(shù)據(jù)庫(kù),應(yīng)該怎么解決這個(gè)問(wèn)題?
