本文介绍了如何将这个元组的元组转换成元素的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 tuple 的元组:

  TupleOfTuples = ('Venue1','Name1'),('Venue1','Name2'),
('Venue2','Name3'),('Venue3','Name4'),
Venue3','Name5'),('Venue3','Name6'))



转换它得到这样的结果:

 输出=(('Venue1',2),('Venue2',1 ),('Venue3',3))

在这种情况下, 包含('Venue1',2),例如,其中 2 的'Venue1'发生在 TupleOfTuples 。



我尝试使用 len()来计算出现次数,但它不工作,因为 TupleOfTuples 不是

解决问题。



如何在Python2.7中做到这一点?方案

使用以计算您的出现次数:

  

输出= Counter(t [0] for t in TupleOfTuples).items()


$ b b

A Counter()是一个字典,其中键映射到计数;通过传递一个生成器表达式它会做你的计数。因为它是一个字典子类, dict.items()可以用于产生(key,count)



演示:

只要调用 tuple()

 >>> from collections import Counter 
>>>> TupleOfTuples =((Venue1','Name1'),('Venue1','Name2'),('Venue2','Name3'),'Venue3','Name4' '),('Venue3','Name6'))
>>>> Counter(t [0] for t in TupleOfTuples).items()
[('Venue1',2),('Venue3',3),('Venue2',1)]


I have this tuple of tuples:

TupleOfTuples = (('Venue1', 'Name1'), ('Venue1', 'Name2'), 
                 ('Venue2', 'Name3'), ('Venue3', 'Name4'), 
                 ('Venue3', 'Name5'), ('Venue3', 'Name6'))

I want to convert it to get a result like this:

Output = (('Venue1', 2), ('Venue2', 1), ('Venue3', 3))

In this case, Output contains ('Venue1', 2), for example, where 2 is the number of times 'Venue1' occurred in TupleOfTuples.

I tried using len() to count the number of occurrences, but it does not work given that TupleOfTuples is not a single tuple but a tuple of tuples.

How can this be done in Python2.7?

解决方案

Use collections.Counter() to count how many occurrences you have:

from collections import Counter

Output = Counter(t[0] for t in TupleOfTuples).items()

A Counter() is a dictionary where keys are mapped to counts; by passing in a generator expression it will do the counting for you. Because it is a dictionary subclass, dict.items() can then be used to produce a list of (key, count) tuples.

This does produce a list; simply call tuple() on that if you insist on having a tuple here.

Demo:

>>> from collections import Counter
>>> TupleOfTuples = ( ('Venue1', 'Name1'), ('Venue1', 'Name2'), ('Venue2', 'Name3'), ('Venue3', 'Name4'), ('Venue3', 'Name5'), ('Venue3', 'Name6') )
>>> Counter(t[0] for t in TupleOfTuples).items()
[('Venue1', 2), ('Venue3', 3), ('Venue2', 1)]

这篇关于如何将这个元组的元组转换成元素的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:35