gpt4 book ai didi

python - 在python中循环更新字典键

转载 作者:太空狗 更新时间:2023-10-30 02:54:16 26 4
gpt4 key购买 nike

我想用它的新键 k_new 更新我的字典 c 的键。尽管我指的是不同的堆栈溢出问题,例如 this它没有得到更新。请告诉我哪里做错了。

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
c = {'apples': 3, 'biscuits and tea': 3, 'oranges and onions': 4}
for k in c:
splits=k.split()
k_new= " ".join(lemmatizer.lemmatize(w.lower()) for w in splits)
c[k_new] = c.pop(k)
print(c)

PS:我也用过:

c[k_new] = c[k]
del c[k]

然后我得到 RuntimeError: dictionary changed size during iteration

请帮帮我

最佳答案

在迭代字典的同时更新字典:

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
c = {'apples': 3, 'biscuits and tea': 3, 'oranges and onions': 4}
for k in c: # iterate over c
splits=k.split()
k_new= " ".join(lemmatizer.lemmatize(w.lower()) for w in splits)
c[k_new] = c.pop(k) # update (two times) c
print(c)

在迭代集合时更新集合通常是一个非常糟糕的主意。大多数数据结构并非设计用于处理此问题。

但是您可以构造一个新字典:

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
c = {'apples': 3, 'biscuits and tea': 3, 'oranges and onions': 4}
<b>c_new = {}</b>
for k in c:
splits=k.split()
k_new= " ".join(lemmatizer.lemmatize(w.lower()) for w in splits)
<b>c_new</b>[k_new] = <b>c[k]</b>
print(<b>c_new</b>)

我们可以通过使用字典理解使它更优雅:

{" ".join(lemmatizer.lemmatize(w.lower()) for w in k.split()): v
for k,v in c.items()}

这个单行代码构建了一个新字典,我们在其中迭代 c 的键值对 k,v,并添加一个键 "".join (lemmatizer.lemmatize(w.lower()) for w in k.split()) 我们与值 v 相关联。

关于python - 在python中循环更新字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46560248/

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