【问题标题】:Access value from tuple by key in python在python中按键访问元组中的值
【发布时间】:2015-02-28 05:48:31
【问题描述】:

我有概率哈希图,其中键是概率值,值是它们的类型。为了获得最高概率,我对哈希图进行了排序,但我不知道如何访问具有最高键值的值。

probability = {classify_email(mailmessage, android_term_df):"android" ,
                           classify_email(mailmessage, spam_term_df):"spam" ,
                           classify_email(mailmessage, c_term_df):"c" ,
                           classify_email(mailmessage, cplus_term_df):"cplus",
                           classify_email(mailmessage, java_term_df):"java",
                           classify_email(mailmessage, php_term_df):"php" ,
                           classify_email(mailmessage, easyham_term_df):"ham" 
                           }
            sorted_probability = sorted(probability.items(), key=operator.itemgetter(0))

【问题讨论】:

  • 你的hashmap很奇怪。通常,键是常量,值是可变的。

标签: python hashmap


【解决方案1】:

你甚至不需要排序:

highest_probabilty_type = probability[max(probability.keys())]

【讨论】:

  • 太棒了!非常感谢:)
【解决方案2】:

如果你的 2 个类具有完全相同的概率,那么只有其中一个会保留在这样的代码中的字典中。

你应该做的是使用类作为键概率 作为价值

from operator import itemgetter

dfs = {
    "android": android_term_df,
    "spam": spam_term_df,
    "c": c_term_df,
    "cplus": cplus_term_df,
    "java": java_term_df,
    "php": php_term_df,
    "ham": ham_term_df,
}

probabilities = { cls: classify_email(mailmessage, dfs[cls]) for cls in dfs }

# now they are classes -> probability
max_cls, max_prob = max(probabilities.items(), key=itemgetter(1))

或者,如果您需要排序的分布列表,请将它们放入 (probability, class) 元组列表中:

probabilities = [ (classify_email(mailmessage, dfs[cls], cls)) for cls in dfs ]
probabilities.sort()

请注意,与您的原始示例不同,您不会在重复的情况下丢失任何对。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多