Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用list if语句填充字典_Python_List_Function_Dictionary - Fatal编程技术网

Python 用list if语句填充字典

Python 用list if语句填充字典,python,list,function,dictionary,Python,List,Function,Dictionary,我不明白字典“count”是如何被“List”填充和引用的 具体来说,为什么列表中的项目('list')会通过“if item in count”语句添加到字典中('count') “count”字典一开始是空的,没有“append”函数 append functionality not supported for empty dict and can be achieved by count[item] += 1 下面是python函数: def countDuplicates(List):

我不明白字典“count”是如何被“List”填充和引用的


具体来说,为什么列表中的项目('list')会通过“if item in count”语句添加到字典中('count')

“count”字典一开始是空的,没有“append”函数

append functionality not supported for empty dict and can be achieved by count[item] += 1 下面是python函数:

def countDuplicates(List):
    count = {}
    for item in List:
        if item in count:
            count[item] += 1
        else:
            count[item] = 1
    return count

print(countDuplicates([1, 2, 4, 3, 2, 2, 5]))

输出:
{1:1,2:3,3:1,4:1,5:1}
这就是为什么它会检查计数中的项目,如果这是您第一次看到计数,它将失败(因为它还没有在字典中定义)

在这种情况下,它将使用
count[item]=1
来定义它


下次看到计数时,它将已经被定义(为1),因此您可以使用
count[item]+=1
增加它,即
count[item]=count[item]+1
,即
count[item]=1+1
,等等。您可以手动运行代码以查看其工作方式

count = {} // empty dict
遍历列表的第一个元素是1,它会检查此行中的dict,以查看该元素是否在之前添加到dict中

if item in count:
它不在计数中,因此它将元素放入列表,并在此行中使其值为1

 count[item] = 1 //This appends the item to the dict as a key and puts value of 1
计数变成

count ={{1:1}}
然后它遍历下一个元素,即2个相同的故事计数

count={{1:1},{2:1}}
count = {{1:1},{2:2},{4,1}}
下一项是4

count = {{1:1},{2:1},{4,1}}
下一项是2,在本例中,我们的dict中有2,所以在这一行中它的值增加了1

     count[item] += 1
计数变成

count={{1:1},{2:1}}
count = {{1:1},{2:2},{4,1}}

它会一直持续到列表完成

具体来说,为什么列表中的项目(“list”)会用“if item in count”语句添加到字典(“count”)中?

`检查元素是否已添加到字典中,如果存在,则增加与项关联的值。
例子:
[1,2,4,3,2,2,5]
dict[item]=1值为“1”-->否则块,dict中不存在键“1”(item),请将出现项添加到并按“1”递增

当列表[1,2,4,3,2,2,5]中的元素已存在于dict中时 计数[项目]+=1-->增加每个项目的出现次数`

=================

“count”字典一开始是空的,没有“append”函数。 append functionality not supported for empty dict and can be achieved by count[item] += 1
空dict不支持追加功能,可通过以下方式实现 计数[项目]+=1

此代码是否有问题?这是你的密码吗?欢迎使用SO。请花点时间阅读它所包含的链接。你可能还想投入一些时间来解决这个问题。我认为问题很清楚。第2段询问
中的
做了什么,第3段询问如何在没有
附加的情况下向
dict
添加内容。Python内置了实现相同任务的功能谢谢!现在有道理了!“if item in count”将首次失败,并首次使用列表中的“item”和“else:count[item]”分配[count],这是第一次遇到列表中唯一的项。谢谢@Alper first Kaya!这正是我想要的解释/走查!我想告诉你们的是,你们并不孤单:P
来自集合进口柜台;重复项=计数器([1,2,4,3,2,2,5])
谢谢@slackmart。在这种情况下,“收藏”库肯定也会起作用。我发布这个问题是为了理解将列表中的项目分配到带有if语句的字典中。这绝对是一门基础课,但却是一堂值得学习的编程课。