需要帮助来理解这个字典上的for循环的输出

时间:2017-07-20 08:29:17

标签: python dictionary

以下是代码:

 def list_to_dict(li): 
            dct = {} 
            for item in li:
                dct[item] = dct.get(item,0)+1
                print(dct)
            return dct 

    li = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 7] 
    print(list_to_dict(li))

以下是输出。我无法理解输出是如何产生的?

{1: 1}
{1: 2}
{1: 3}
{1: 3, 2: 1}
{1: 3, 2: 1, 3: 1}
{1: 3, 2: 1, 3: 2}
{1: 3, 2: 1, 3: 2, 4: 1}
{1: 3, 2: 1, 3: 2, 4: 2}
{1: 3, 2: 1, 3: 2, 4: 3}
{1: 3, 2: 1, 3: 2, 4: 4}
{1: 3, 2: 1, 3: 2, 4: 5}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 1}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 2}
{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 2}

3 个答案:

答案 0 :(得分:1)

def list_to_dict(li): 
            dct = {} 
            #loop is running over all item passed.
            for item in li:
                dct[item] = dct.get(item,0)+1
                # .get method  "dict.get(key, default=None)"
                # here default you have provided as 0, means if the
                # key is present than get will return the value
                # of that key otherwise 0
                #
                # So now if the number is present you will increase the value by 1
                # otherwise you will assign 1 as the value for the new key found in the array
                #
                #look more for .get method of dictionary you will be clear on this

                print(dct)
            return dct 

li = [1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 7, 7] 
print(list_to_dict(li))

答案 1 :(得分:1)

输出的前15行来自循环内部的打印功能(第5行)。这些来自转换的每个阶段。输出中唯一重要的部分是最后一行{1: 3, 2: 1, 3: 2, 4: 5, 5: 1, 6: 1, 7: 2}。这是函数的实际输出。因此,dict中的每个项目都有一个列表中的数字索引以及该数字出现的次数。因此,一个更简单的示例是列表[1, 1, 1, 5],它将返回{1:3, 5:1}。部分“1:3”表示数字1出现3次,部分“5:1”表示数字5出现一次。

答案 2 :(得分:-1)

首先, Python中的字典不能有重复的键, 代码计算列表中的所有项目。 如果你想知道为什么你会以这种方式看到输出,那么也许你应该从函数中取出print语句,并在主代码循环中只有一个打印函数。