【问题标题】:Variable not reassigned when changed in for loop在 for 循环中更改时未重新分配变量
【发布时间】:2019-11-10 14:21:18
【问题描述】:

此代码的目标是计算给定列表中出现次数最多的单词。我计划通过遍历字典来做到这一点。如果一个单词出现的次数比存储在变量 rep_num 中的值多,它就会被重新分配。目前,变量 rep_num 保持为 0,并且不会重新分配给单词在列表中出现的次数。我相信这与尝试在 for 循环中重新分配它有关,但我不确定如何解决此问题。

def rep_words(novel_list):
    rep_num=0
    for i in range(len(novel_list)):
        if novel_list.count(i)>rep_num:
            rep_num=novel_list.count(i)
    return rep_num
novel_list =['this','is','the','story','in','which','the','hero','was','guilty']

在给定的代码中,应该返回 2,但返回的是 0。

【问题讨论】:

  • count是一个整数 (i),它根本不会出现在你的列表中。

标签: python for-loop variables assign


【解决方案1】:

你的函数有错误(你计算的是索引,而不是值),这样写:

def rep_words(novel_list):
    rep_num=0
    for i in novel_list:
        if novel_list.count(i)>rep_num:  #you want to count the value, not the index
            rep_num=novel_list.count(i)
    return rep_num

或者你也可以试试这个:

def rep_words(novel_list):
    rep_num=0
    for i in range(len(novel_list)):
        if novel_list.count(novel_list[i])>rep_num:
            rep_num=novel_list.count(novel_list[i])
    return rep_num

【讨论】:

    【解决方案2】:

    在你的 for 循环中,你正在迭代数字而不是列出元素本身,

    def rep_words(novel_list):
        rep_num=0
        for i in novel_list:
            if novel_list.count(i)>rep_num:
                rep_num=novel_list.count(i)
        return rep_num
    

    【讨论】:

      【解决方案3】:

      您正在迭代一个数字范围,counting 整数 i,列表中根本不存在任何值。试试这个,它返回最大频率,以及可选的出现多次的单词列表。

      novel_list =['this','is','the','story','in','which','the','hero','was','guilty']
      
      def rep_words(novel_list, include_words=False):
          counts = {word:novel_list.count(word) for word in set(novel_list)}
          rep = max(counts.values())
          word = [k for k,v in counts.items() if v == rep]
          return (rep, word) if include_words else rep
      
      >>> rep_words(novel_list)
      2
      >>> rep_words(novel_list, True)
      (2, ['the'])
      >>> rep_words('this list of words has many words in this list of words and in this list of words is this'.split(' '), True)
      (4, ['words', 'this'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-02
        • 2012-02-26
        • 1970-01-01
        • 2015-07-07
        • 1970-01-01
        相关资源
        最近更新 更多