suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Bezüglich des Problems, die Anzahl verschiedener numerischer Typen in einer Liste von Ganzzahlen in Python zu zählen.

Im folgenden Code wird kind_num verwendet, um die Ganzzahlen mit mehreren unterschiedlichen Werten in der Ganzzahlliste zu zählen.

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])

Aber die zweite for-Schleife wurde vorzeitig beendet, bevor die Werte in den Bonbons vervollständigt wurden. ? ?

大家讲道理大家讲道理2789 Tage vor998

Antworte allen(3)Ich werde antworten

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-22 11:54:27

    在循环里不要去remove

    如果你仅仅是想实现统计不同种类的值

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

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-06-22 11:54:27

    candies.remove(candy) 第一次执行 Ok, candy被remove; 由于while (True), 在同一次For 循环中 会无限remove 这个candy,但是这个candy 已经在第一次被移除了。所以break.

    Antwort
    0
  • phpcn_u1582

    phpcn_u15822017-06-22 11:54:27

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

    Antwort
    0
  • StornierenAntwort