【问题标题】:Get Counter most common key value获取 Counter 最常用的键值
【发布时间】:2020-08-16 10:45:27
【问题描述】:

我只需要打印most_common(1) 返回的最常见元组的键,但它返回的是一个元组。我怎样才能得到钥匙?

对于给定的示例,它应该只打印The System,现在我得到('The System', 3)。我无法在文档中找到可以做到这一点的函数。

from collections import Counter

def main():

cmp_sub_list = ['System', 'System', 'The System', 'Customer', 'The System', 'The System']
most_common_subject = Counter(cmp_sub_list).most_common(1)
print(most_common_subject)

if __name__ == '__main__':
    main()

【问题讨论】:

  • print(most_common_subject[0][0]) ?

标签: python string list counter


【解决方案1】:

可以访问元组索引,即:

most_common_subject = Counter(cmp_sub_list).most_common(1)[0][0]
# The System

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多