Python元组操作和计数 [英] Python tuple operations and count

查看:35
本文介绍了Python元组操作和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下元组.我想构建一个字符串,按照输出中的说明输出.我想计算与a"对应的所有元素,即,a"出现了多少个 k1,等等.什么是最简单的方法

I have the following tuple.I want to build a string which outputs as stated in output.I want count all the elements corresponding to 'a' i.e, how many k1 occured w.r.t 'a' and so on .What is the easiest way to do this

a=[('a','k1'),('b','k2'),('a','k2'),('a','k1'),('b','k2'),('a','k1'),('b','k2'),('c','k3'),('c','k4')]

输出应该是一个字符串 output=""

Output should be in a string output=""

 a k1  3
 a k2  1
 b k1  1
 b k2  3
 c k3  1
 c k4  1

推荐答案

您可以使用 defaultdict.默认字典的工作方式与普通字典类似,不同之处在于它有一个用于空键存储的默认值,因此您可以在迭代数据集时轻松增加计数器.

You can do the addition portion easily with defaultdict. The default dict works like a normal dictionary, except it has a default value for empty key stores so you can easily increment your counter when you iterate over your data set.

a=[('a','k1'),('b','k2'),('a','k2'),('a','k1'),('b','k2'),('a','k1'),('b','k2'),('c','k3'),('c','k4')]
from collections import defaultdict
b = defaultdict(int)
for item in a:
    b[item] += 1

print b
defaultdict(<type 'int'>, {('a', 'k2'): 1, ('c', 'k3'): 1, ('b', 'k2'): 3, ('a', 'k1'): 3, ('c', 'k4'): 1})

为了漂亮地打印它,只需迭代结果数据并按照您想要的方式打印.

And for pretty printing it, just iterate over the resulting data and print it how you want.

for key, value in b.iteritems():
    print '%s %s %s' % (key[0], key[1], value)

这篇关于Python元组操作和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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