m0_58473424
2021-05-21 08:21
采纳率: 83.3%
浏览 59

统计元组中的信息到字典

现有三位同学参加了比赛,记录列表存储在names中。 names=['Li','Zhang','Wang','Zhang','Li','Wang','Li','Wang','Wang'] 请统计每个学生参加比赛的次数并记录到字典d中并输出,结果如下: {'Li': 3, 'Zhang': 2, 'Wang': 4}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • 小P聊技术 2021-05-21 08:41
    已采纳
    # encoding: utf-8
    """
    @version: 1.0
    @author: AusKa_T
    @file: ttt
    @time: 2021/5/17 0017 16:45
    """
    from collections import Counter
    
    names=['Li','Zhang','Wang','Zhang','Li','Wang','Li','Wang','Wang']
    b = Counter(names)
    print(b)
    

    运行结果:

    F:\JAVA\PyCharm\Python37\python.exe F:/JAVA/PyCharm/PycharmProjects/http_site/email/ttt.py
    Counter({'Wang': 4, 'Li': 3, 'Zhang': 2})
    
    Process finished with exit code 0
    
    点赞 打赏 评论
  • 吃肉的小馒头 2021-05-21 09:12
    dic = {}
    for i in names:
        if i not in dic:
            dic[i] = 1
        else:
            dic[i] += 1
    print(dic)
    点赞 打赏 评论

相关推荐 更多相似问题