Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.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 使用If条件在字典上迭代的函数_Python_Python 3.x - Fatal编程技术网

Python 使用If条件在字典上迭代的函数

Python 使用If条件在字典上迭代的函数,python,python-3.x,Python,Python 3.x,我对下面的代码有一个问题,它基本上是一个包含两个参数的函数,一个是列,一个是数据帧,我很难理解遍历列并检查列中的值是否是空字典“langs_counts”中的键的for循环,当它是一个空字典时,如何检查它,请向我解释for循环,以及为什么我们在方括号之间放“entry” for entry in col: if entry in langs_count.keys(): langs_count[entry] += 1 else: lang

我对下面的代码有一个问题,它基本上是一个包含两个参数的函数,一个是列,一个是数据帧,我很难理解遍历列并检查列中的值是否是空字典“langs_counts”中的键的for循环,当它是一个空字典时,如何检查它,请向我解释for循环,以及为什么我们在方括号之间放“entry”

for entry in col:
   if entry in langs_count.keys():
            langs_count[entry] += 1
   else:
            langs_count[entry] = 1

    # Define count_entries()
    def count_entries(df, col_name):
    """Return a dictionary with counts of 
    occurrences as value for each key."""

    # Initialize an empty dictionary: langs_count
        langs_count = {}

        # Extract column from DataFrame: col
        col = df[col_name]

        # Iterate over lang column in DataFrame
        for entry in col:
            # If the language is in langs_count, add 1
            if entry in langs_count.keys():
                langs_count[entry] += 1
            # Else add the language to langs_count, set the value to 1
            else:
                langs_count[entry] = 1


    # Return the langs_count dictionary
    return langs_count   

    # Call count_entries(): result
    result = count_entries(tweets_df, 'lang')

    # Print the result
    print(result)

为什么我们把“条目”放在方括号中

方括号中的东西叫做钥匙

这只是索引的简化:

示例代码:

a={'a':1,'b':2,'c':[1,2]}

a[“d”]=5,在机器中,它变成:a.。_u设置项_uuu(“d”,5)


如果“d”不作为键存在,它将创建一个键。如果它存在,则当
lang\u count
为空字典时,函数将为其分配一个新值,则lang\u count.keys()中的
条目始终为False。然后指令
langs\u count[entry]=1
创建包含与值1关联的
entry
内容的键。它实际上是通过计算数据(
col
)中某个
键的出现次数来构建
lang\u count
字典。行
langs_count[entry]=1
将在该字典中创建一个条目,如果该条目不存在,则使用
entry
在该字典中创建该条目。您可以使用计数器而不是使用字典来计算内容:@toti08谢谢您的回答,所以[entry]是否每次循环进行时密钥都会更改,如果为真,则会将当前密钥的值增加1,否则将从当前条目生成一个新密钥,并将其值设置为1,我说的对吗?@Moberg我会研究一下,但这只是在线课程中的一个练习问题,我正在努力理解它,谢谢