计算元组列表中的重复项 [英] Count the duplicates in a list of tuples

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

问题描述

我有一个元组列表:a = [(1,2),(1,4),(1,2),(6,7),(2,9)]我想检查每个元组的各个元素之一是否与另一个元组中的相同位置/元素匹配,以及发生了多少次.

I have a list of tuples: a = [(1,2),(1,4),(1,2),(6,7),(2,9)] I want to check if one of the individual elements of each tuple matches the same position/element in another tuple, and how many times this occurs.

例如:如果某些元组中只有第一个元素具有重复项,则返回该元组及其重复次数. 我可以使用以下代码做到这一点:

For example: If only the 1st element in some tuples has a duplicate, return the tuple and how many times it's duplicated. I can do that with the following code:

a = [(1,2), (1,4), (1,2), (6,7), (2,9)]

coll_list = []
for t in a:
    coll_cnt = 0
    for b in a:
        if b[0] == t[0]:
            coll_cnt = coll_cnt + 1
    print "%s,%d" %(t,coll_cnt)
    coll_list.append((t,coll_cnt))

print coll_list

我想知道是否有更有效的方法吗?

I want to know if there is a more effective way to do this?

推荐答案

使用集合库.在下面的代码val_1中,val_2为您分别提供了元组的每个第一元素和第二元素的副本.

use collections library. In the following code val_1, val_2 give you duplicates of each first elements and second elements of the tuples respectively.

import collections
val_1=collections.Counter([x for (x,y) in a])
val_2=collections.Counter([y for (x,y) in a])

>>> print val_1
<<< Counter({1: 3, 2: 1, 6: 1})

这是每个元组的第一个元素的出现次数

This is the number of occurrences of the first element of each tuple

>>> print val_2
<<< Counter({2: 2, 9: 1, 4: 1, 7: 1})

这是每个元组的第二个元素的出现次数

This is the number of occurrences of the second element of each tuple

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

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