如何计算元组列表中的重复项数量? [英] How to count number of duplicates in a list of tuples?

查看:131
本文介绍了如何计算元组列表中的重复项数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元组的python列表,如下所示:

I have a python list of tuples as shown below:

listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')] 

我想计算此元组列表中重复项的数量,并希望输出如下:

I want to count the number of duplicates in this list of tuples and want the output as follows:

A -> B 2
C -> D 2
E -> F 1
G -> H 1

如何在python中执行此操作?我当时正在考虑使用计数器,但不确定.谢谢.

How can I do this in python? I was thinking about using counter but not sure. Thank You.

推荐答案

您可以使用Counter

listoftups = [('A', 'B'), ('C','D'), ('E','F'), ('G','H'), ('A','B'), ('C','D')] 
from collections import Counter 
for k, v in Counter(listoftups).most_common():
    print "{} -> {} {}".format(k[0], k[1], v)

输出

A -> B 2
C -> D 2
G -> H 1
E -> F 1

这篇关于如何计算元组列表中的重复项数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆