Python 需要帮助了解此字典上此for循环的输出吗
代码如下:Python 需要帮助了解此字典上此for循环的输出吗,python,dictionary,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_t
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}
首先,,
Python中的字典不能有重复的键,
该代码统计列表中的所有项目。
如果您想知道为什么会以这种方式看到输出,那么您可能应该将print语句从函数中取出,在主代码循环中只有一个print函数。输出的前15行来自循环中的print函数(第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出现一次。您是否知道词典
不能有重复的键?这将统计列表中的项目。什么,你到底不明白?你必须明确你的问题。导入集合;集合。计数器([1,1,1,2,3,3,4,4,4,4,4,5,6,7])
Out[…]:计数器({1:3,2:1,3:2,4:5,5:1,6:1,7:2})
^。我现在得到了答案。
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))