【问题标题】:How to convert a list into a dictionary in python [duplicate]如何在python中将列表转换为字典[重复]
【发布时间】:2013-11-12 17:52:03
【问题描述】:

我有以下清单:

pet = ['cat','dog','fish','cat','fish','fish']

我需要将它转换成这样的字典:

number_pets= {'cat':2, 'dog':1, 'fish':3}

我该怎么做?

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    正如@hcwhsa 所说,您可以使用collections.Counter。但是如果你想编写自己的类,你可以这样开始:

    class Counter(object):
    
        def __init__(self, list):
    
            self.list = list
    
        def count(self):
    
            output = {}
            for each in self.list:
                if not each in output:
                    output[each] = 0
                output[each]+=1
            return output
    
    >>> Counter(['cat', 'dog', 'fish', 'cat', 'fish', 'fish']).count()
    >>> {'fish': 3, 'dog': 1, 'cat': 2}
    

    【讨论】:

      【解决方案2】:

      使用collections.Counter:

      >>> from collections import Counter
      >>> pet = ['cat','dog','fish','cat','fish','fish']
      >>> Counter(pet)
      Counter({'fish': 3, 'cat': 2, 'dog': 1})
      

      【讨论】:

        猜你喜欢
        • 2016-01-10
        • 2017-07-31
        • 2021-04-25
        • 2019-11-18
        • 2018-06-04
        • 1970-01-01
        • 1970-01-01
        • 2019-09-28
        • 2017-12-04
        相关资源
        最近更新 更多