【问题标题】:Missing keys from dictionary counting words in list字典中缺少关键字来计算列表中的单词
【发布时间】:2023-01-01 20:35:22
【问题描述】:

我的输出不完整。有 3 个元素不算数。

# A programm to count words in a string and put them in a dictionary as key = word and value = count

def word_in_str (S):
    dict_s = {}   # make a empty dict

    s = S.lower() # make string lowercase
    l = s.split() # split string into a list and separate theme by spase

    print (l)     # original list contain all words

    for word in l:
        counter = l.count (str(word)) 

        print (str(word))  # for testing the code, it's value = count
        print (counter)    # for testing the code, it's key = word

        dict_s[str(word)] = counter 

        l[:] = (value for value in l if value != str(word)) #delete the word after count it

        print (l)          # for testing the code, it's the list after deleting the word        

    print (dict_s)         # main print code, but there is no ('when', 'young', 'and') in result


if __name__ == '__main__':    
    word_in_str ('I am tall when I am young and I am short when I am old')

此代码的输出是:

['i', 'am', 'tall', 'when', 'i', 'am', 'young', 'and', 'i', 'am', 'short', 'when', 'i', 'am', 'old']
i
4
['am', 'tall', 'when', 'am', 'young', 'and', 'am', 'short', 'when', 'am', 'old']
tall
1
['am', 'when', 'am', 'young', 'and', 'am', 'short', 'when', 'am', 'old']
am
4
['when', 'young', 'and', 'short', 'when', 'old']
short
1
['when', 'young', 'and', 'when', 'old']
old
1
['when', 'young', 'and', 'when'] <==what happened to this words?
{'i': 4, 'tall': 1, 'am': 4, 'short': 1, 'old': 1}  <==result without the words above

【问题讨论】:

  • 尝试将输出格式化为代码以使其看起来正确。更清楚地区分什么是真正的输出,它的哪一部分是错误的,什么是预期的。
  • 您到底希望l[:] = 行做什么?
  • 迭代列表时不应修改列表。
  • 我建议首先创建第二个没有重复的列表,然后在修改原始列表的同时迭代此列表。
  • 使用正确的大写字母。更具体地说明您的主题。

标签: python list dictionary


【解决方案1】:

我认为你过度思考了这个问题。 Counter 已经计算了一个 iterable 的元素,它是一种 dict

from collections import Counter

def word_in_str(S):
    return dict(Counter(S.split()))

您的代码的问题是您的 for 循环结束了 l,但是您正试图“删除”并重新分配 l[:],而您并不真正需要这样做。只需计算并存储字典条目即可。

【讨论】:

  • 谢谢@OneCricketeer
  • 请随时使用帖子旁边的复选标记接受答案
【解决方案2】:
def word_in_str (S):
    dict_s = {}
    s = S.lower()
    l = s.split()
    for word in l:
        counter = l.count (word)
        dict_s[word] = counter 
    print (dict_s)
    
word_in_str ('I am tall when I am young and I am short when I am old')

【讨论】:

  • 在查找计数和更新字典之前,您应该检查if word not in dict_s。否则,您将不必要地计算重复项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-19
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
相关资源
最近更新 更多