在 Python 中计算元组内的项目 [英] Counting items inside tuples in Python

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

问题描述

我对 python 相当陌生,我无法弄清楚如何执行以下操作.

我有一个 (word, tag) 元组列表

a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('的', 'DT')]

我正在尝试查找已分配给每个单词的所有标签并收集它们的计数.例如,单词run"两次被标记为名词",一次被标记为动词".

澄清:我想创建另一个包含 (word, tag, count) 的元组列表

解决方案

您可以使用 collections.Counter:

<预><代码>>>>进口藏品>>>a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]>>>counter = collections.Counter(a)Counter({('Run', 'Noun'): 2, ('Run', 'Verb'): 1, ... })>>>结果 = {}>>>for (tag, word), count in counter.items():... result.setdefault(tag, []).append({word: count})>>>打印(结果){'Run': [{'Noun': 2}, {'Verb': 1}], 'The': [{'Article': 1}, {'DT': 1}]}

I am fairly new to python and I could not figure out how to do the following.

I have a list of (word, tag) tuples

a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]

I am trying to find all tags that has been assigned to each word and collect their counts. For example, word "run" has been tagged twice to 'Noun' and once to 'Verb'.

To clarify: I would like to create another list of tuples that contains (word, tag, count)

解决方案

You can use collections.Counter:

>>> import collections

>>> a = [('Run', 'Noun'),('Run', 'Verb'),('The', 'Article'),('Run', 'Noun'),('The', 'DT')]
>>> counter = collections.Counter(a)
Counter({('Run', 'Noun'): 2, ('Run', 'Verb'): 1, ... })

>>> result = {}
>>> for (tag, word), count in counter.items():
...     result.setdefault(tag, []).append({word: count})

>>> print(result)
{'Run': [{'Noun': 2}, {'Verb': 1}], 'The': [{'Article': 1}, {'DT': 1}]}

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

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