python - 计算元组列表中的重复项

标签 python list tuples

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

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

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

我想知道是否有更有效的方法来做到这一点?

最佳答案

您可以使用 Counter

from collections import Counter
a = [(1,2),(1,4),(1,2),(6,7),(2,9)]
counter=Counter(a)
print counter

这将输出:

Counter({(1, 2): 2, (6, 7): 1, (2, 9): 1, (1, 4): 1})

它是一个类似字典的对象,以项目(在本例中为元组)作为键,值包含该键被看到的次数。您的 (1,2) 元组被看到两次,而所有其他元组只被看到一次。

>>> counter[(1,2)]
2

如果您对元组的每个单独部分感兴趣,您可以对元组中的每个元素使用相同的逻辑。

first_element = Counter([x for (x,y) in a])
second_element = Counter([y for (x,y) in a])

first_elementsecond_element 现在包含一个 Counter 值在 per element 中出现的次数元组

>>> first_element
Counter({1: 3, 2: 1, 6: 1})
>>> second_element
Counter({2: 2, 9: 1, 4: 1, 7: 1})

同样,这些是类似字典的对象,因此您可以直接检查特定值出现的频率:

>>> first_element[2]
1

在元组列表的第一个元素中,值 2 出现了 1 次。

关于python - 计算元组列表中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207601/

相关文章:

从 R 中的单元格中删除重复的单词

python - 如何在 python 中解压嵌套元组?

python - Argparse:可选参数,不同位置参数不同

python - 构建 python 项目的非常*简单*的方法是什么?

python - Windows服务在Anaconda环境中运行?

python - 如何打印出具有特定质量的列表?

python - 如何将大列表拆分成行?

python - 遍历元组并计算数字的百分比

c++ - 在 C++ 中随机抽取具有权重的元组 vector

python - 用python调用命令exe