【问题标题】:how to count duplicates in a list of tuples and append it as a new value如何计算元组列表中的重复项并将其附加为新值
【发布时间】:2023-01-26 17:43:39
【问题描述】:
output = [('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO')]

所以上面的列表中总共有 6 组 ('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO')

所以我期待这样的输出~

预期输出 = [('studentA','ISDF',6), ('studentB','CSE',6),('studentC','BIO',6)]

格式应为[('student', 'department', total count)]

【问题讨论】:

    标签: python list scripting


    【解决方案1】:

    你可以使用Counter

    from collections import Counter
    
    output = [('studentA', 'ISDF'), ('studentB', 'CSE'), ('studentC', 'BIO'),
              ('studentA', 'ISDF'), ('studentB', 'CSE'), ('studentC', 'BIO'),
              ('studentA', 'ISDF'), ('studentB', 'CSE'), ('studentC', 'BIO'),
              ('studentA', 'ISDF'), ('studentB', 'CSE'), ('studentC', 'BIO'),
              ('studentA', 'ISDF'), ('studentB', 'CSE'), ('studentC', 'BIO'),
              ('studentA', 'ISDF'), ('studentB', 'CSE'), ('studentC', 'BIO')]
    
    counts = Counter(output)
    print(counts)
    print([k + (v, ) for k, v in counts.items()])
    

    出去:

    Counter({('studentA', 'ISDF'): 6, ('studentB', 'CSE'): 6, ('studentC', 'BIO'): 6})
    [('studentA', 'ISDF', 6), ('studentB', 'CSE', 6), ('studentC', 'BIO', 6)]
    

    【讨论】:

      【解决方案2】:

      使用集合中的 Counter() 和列表理解

      from collections import Counter
      
      count = Counter(output)
      exp_output = [(key[0], key[1], value) for key, value in count.items()]
      print(exp_output)
      

      [('studentA', 'ISDF', 6), ('studentB', 'CSE', 6), ('studentC', 'BIO', 6)]
      

      【讨论】:

        【解决方案3】:

        尝试这个:

        sorted([tuple(list(item)+[output.count(item)]) for item in set(output)])
        

        【讨论】:

          猜你喜欢
          • 2022-01-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-09
          • 1970-01-01
          • 2016-04-02
          • 1970-01-01
          相关资源
          最近更新 更多