【问题标题】:How to return the smallest average within a nested loop如何在嵌套循环中返回最小平均值
【发布时间】:2012-04-26 07:43:35
【问题描述】:

我需要返回列表中单词相似度的最小平均值(我可以这样做),但我不知道如何将单词字符串值分配给平均值,例如在 ['my', 'bro', 'myline'] 的列表中当然,兄弟的比较值最少,因此我需要将 'bro' 与比较值一起返回(我已经知道如何......只需要知道如何在嵌套循环中分配值)。

final_tup = ()
ave_list = []
for word in final_list:
    word1 = word
    sum = 0
    for word in final_list:
        word2 = word
        if word2 != word1:
            num = cossim(word1,word2)
            sum = sum + num
    average = float(sum/(len(final_list)-1))
    ave_list.append(average) 

【问题讨论】:

  • just need to know how to assign values within nested loops 分配到哪里?您到底缺少什么,您的代码似乎 [虽然不是很整洁] 几乎完整。抱歉,我不明白你到底在问什么:\
  • 就不整洁而言:您应该只执行for word1 in final_listfor word2 in final_list 而不是循环遍历word 然后分配。你也应该只做sum += cossim(word1, word2),而不是你目前正在做的事情。
  • 对于每个正在比较的 word1 ..我希望该词被分配或与其 AVERAGE 比较值相关联..

标签: python function loops nested minimum


【解决方案1】:
from operator import itemgetter

# Make the word list.
word_list = ['my', 'bro', 'myline'] 

# Do your code here to create ave_list

# Fetch the min index and min value of ave_list
min_index, minvalue = min(enumerate(ave_list), key = itemgetter(1) )

# Now get the word at the same min index location.
min_word = word_list[min_index] 

【讨论】:

  • 等等,兄弟。当我们有两个相同最小值的索引时会发生什么?我们如何在输出中打印多个单词?
  • 例如,如果索引 1 和 11 具有相同的最小平均值..我如何输出这两个词?
  • 我明天可以修改它,但一种好​​方法是改用 NumPy 数组来存储平均值。
猜你喜欢
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 2019-06-24
  • 1970-01-01
相关资源
最近更新 更多