關于python統計一個整數列表中不同數值種類數的問題。
問題描述
下面這段代碼中,kind_num用于統計那個整數列表中有幾種不同數值的整數。
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])
但是第二個for循環,沒有取完candies里面的值就提前退出了,這是為什么???
問題解答
回答1:在循環里不要去remove
如果你僅僅是想實現統計不同種類的值
#統計出現次數lst = [1,1,2,2,3,3,4,4,5,6]print len(set(lst))#統計每種各出現幾次from collections import Counterprint dict(Counter(lst))回答2:
candies.remove(candy) 第一次執行 Ok, candy被remove; 由于while (True), 在同一次For 循環中 會無限remove 這個candy,但是這個candy 已經在第一次被移除了。所以break.
回答3:from collections import defaultdictd = defaultdict(int)for item in your_list: d[item] += 1 print d
相關文章:
1. html5 - ElementUI table中el-table-column怎么設置百分比顯示。2. python - 使用readlines()方法讀取文件內容后,再用for循環遍歷文件與變量匹配時出現疑難?3. 對mysql某個字段監控的功能4. css3 - less或者scss 顏色計算的知識應該怎么學?或者在哪里學?5. 注冊賬戶文字不能左右分離6. javascript - table列過多,有什么插件可以提供列排序和選擇顯示列的功能7. css - 網頁div區塊 像蘋果一樣可左右滑動 手機與電腦8. javascript - 數組的過濾和渲染9. html - vue項目中用到了elementUI問題10. JavaScript事件
