Python元组操作和计数

编程入门 行业动态 更新时间:2024-10-27 16:24:06
本文介绍了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元组操作和计数

本文发布于:2023-10-13 17:08:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488576.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!