Regarding the problem of counting the number of different numerical types in a list of integers in Python.
大家讲道理
大家讲道理 2017-06-22 11:52:27
0
3
839

In the following code, kind_num is used to count the integers with several different values in the integer list.

class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ loc = len(candies) mol = loc % 2 if 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 = 0 sis_num = loc / 2 for candy in candies: kind_num += 1 while True: try: candies.remove(candy) print candies except ValueError: break if kind_num > sis_num: return sis_num elif kind_num < sis_num: return kind_num else: return sis_num s = Solution() print s.distributeCandies([1,1,2,2,3,3])

But the second for loop exited early before completing the values in the candies. Why is this? ? ?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all (3)
曾经蜡笔没有小新

Don’t remove in the loop

If you just want to count different types of values

#统计出现次数 lst = [1,1,2,2,3,3,4,4,5,6] print len(set(lst)) #统计每种各出现几次 from collections import Counter print dict(Counter(lst))
    Peter_Zhu

    candies.remove(candy) is executed for the first time Ok, candy is removed; due to while (True), this candy will be removed infinitely in the same For loop, but this candy has been removed the first time. So break.

      phpcn_u1582
      from collections import defaultdict d = defaultdict(int) for item in your_list: d[item] += 1 print d
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!