gpt4 book ai didi

python - 在 python 中循环列表并使用 dict 理解创建字典的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 04:07:48 25 4
gpt4 key购买 nike

testWords 是一个包含单词的列表。 setTestWords 是与集合相同的列表。我想使用字典理解创建一本字典,其中我将使用单词作为键,使用计数作为值。我也在使用.count。

示例输出如下:

>>> dictTestWordsCount[:2]
>>> {'hi': 22, 'hello': 99}

这是我正在使用的代码行,但它似乎每次都会使我的笔记本崩溃。

l = {x: testWords.count(x) for x in setTestwords}

最佳答案

不确定是什么原因导致您的笔记本电脑崩溃...

In [62]: txt = "the quick red fox jumped over the lazy brown dog"

In [63]: testWords = txt.split()

In [64]: setTestWords = set(testWords)

In [65]: {x:testWords.count(x) for x in setTestWords}
Out[65]:
{'brown': 1,
'dog': 1,
'fox': 1,
'jumped': 1,
'lazy': 1,
'over': 1,
'quick': 1,
'red': 1,
'the': 2}
<小时/>

或者更好,使用collection.defaultdict

from collections import defaultdict

d = defaultdict(int)

for word in txt.split():
d[word]+=1

print(d)
defaultdict(int,
{'brown': 1,
'dog': 1,
'fox': 1,
'jumped': 1,
'lazy': 1,
'over': 1,
'quick': 1,
'red': 1,
'the': 2})

关于python - 在 python 中循环列表并使用 dict 理解创建字典的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com