• [Python]统计数列中元素出现的次数并进行排序


    题目是:现有数列l1 = ['d', 'f', 'g', 'f', 'e', 'z', 'f', 'a', 'a'] 。请把数列中的元素按照进行排序,并输出次数,重复最多的元素排在前面,程序越简单越好

    方法1:

    1 from collections import Counter
    2 # 根据数列中字母出现的次数和ASCII的大小,进行排序。
    3 l1 = ['d', 'f', 'g', 'f', 'e', 'z', 'f', 'a', 'a'] 
    4 d2 = Counter(l1)
    5 sorted_x = sorted(d2.items(), key=lambda x: x[1], reverse=True)

    方法2:

    l1 = ['d', 'f', 'g', 'f', 'e', 'z', 'f', 'a', 'a']
    set01 = set(l1)
    dict01 = {item: l1.count(item) for item in set01}
    sorted_x = sorted(dict01.items(), key=lambda x: x[1], reverse=True)
    print(sorted_x)
  • 相关阅读:
    jsp第六周作业
    jsp第四周作业
    jsp第一周周作业
    第一次软件测试课堂练习
    4.11jsp
    第六周作业
    第三周jsp作业
    3.10 jsp作业
    3.4软件测试
    JSP第六周作业
  • 原文地址:https://www.cnblogs.com/stanmao/p/10220101.html
Copyright © 2020-2023  润新知