繁体   English   中英

字典理解

[英]Dictionary comprehension

# Initialize an empty dictionary: counts_dict
counts_dict = {}

# Iterate over the file chunk by chunk
for chunk in pd.read_csv('tweets.csv', chunksize=10):

    # Iterate over the column in DataFrame
    for entry in chunk['lang']:
        if entry in counts_dict.keys():
            counts_dict[entry] += 1
        else:
            counts_dict[entry] = 1

# Print the populated dictionary
print(counts_dict)

即使字典counts_dict = {}是一个空字典,谁能解释一下, if-else在下面的代码部分中,如果counts_dict是一个空字典,那么if-else条件如何匹配:-

for entry in chunk['lang']:
    if entry in counts_dict.keys():
        counts_dict[entry] += 1
    else:
        counts_dict[entry] = 1

第一次执行if ,字典将为空,因此entry in count_dicts.keys()将为False 结果,它将执行else:块,该块分配给count_dict[entry] 因此字典不再为空。

在下一次迭代中,如果entry与它刚添加的键相同,则if条件将为True ,并将增加该字典元素。 如果它是另一个键,它将为此创建一个新的字典元素。

这将继续对chunk['lang']每个条目重复-第一次遇到条目时,它将为它创建一个新的字典元素,而重复的条目会将1添加到相应的元素中。 最后,每个字典元素都包含其键的计数。

如果您输入以下内容,就会看到这种情况:

print(count_dict)

for循环中,在if/else块之后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM