久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

關(guān)于python統(tǒng)計(jì)一個整數(shù)列表中不同數(shù)值種類數(shù)的問題。

瀏覽:146日期:2022-06-27 18:17:55

問題描述

下面這段代碼中,kind_num用于統(tǒng)計(jì)那個整數(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])

但是第二個for循環(huán),沒有取完candies里面的值就提前退出了,這是為什么???關(guān)于python統(tǒng)計(jì)一個整數(shù)列表中不同數(shù)值種類數(shù)的問題。

問題解答

回答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)中 會無限r(nóng)emove 這個candy,但是這個candy 已經(jīng)在第一次被移除了。所以break.

回答3:

from collections import defaultdictd = defaultdict(int)for item in your_list: d[item] += 1 print d

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 湖南省| 元谋县| 绥江县| 河间市| 东乡县| 吉安县| 仙桃市| 肇州县| 克什克腾旗| 新晃| 肥东县| 海宁市| 和田县| 邹城市| 曲阜市| 天峻县| 温州市| 汉寿县| 葵青区| 天长市| 潮州市| 青铜峡市| 南通市| 广元市| 古蔺县| 黔南| 泽州县| 阜新市| 彩票| 绥中县| 乐东| 麟游县| 岚皋县| 合阳县| 咸宁市| 巴林左旗| 容城县| 曲水县| 郁南县| 丰台区| 连平县|