python - 迭代列表中的元组并为元组添加权重

标签 python list tuples

我有一个看起来像这样的元组列表。

[(1,2),(3,4),(2,1),(1,2),(2,3),(2,3)]

我想要这样的输出。

[(1,2,2),(3,4,1),(2,1,1),(2,3,2)]

元组中的第三个值是元组在列表中出现的次数。

迭代元组列表并在元组末尾添加值的有效方法是什么? 谢谢。

最佳答案

data = [(1, 2), (3, 4), (2, 1), (1, 2), (2, 3), (2, 3)]
from collections import Counter, OrderedDict

# Use Counter to find the number of times the tuple occured
d = Counter(data)

# Use OrderedDict to maintain the order of occurance
# Get tuples from OrderedDict and get count from d, create a new tuple
print [item + (d[item],) for item in OrderedDict.fromkeys(data)]
# [(1, 2, 2), (3, 4, 1), (2, 1, 1), (2, 3, 2)]

关于python - 迭代列表中的元组并为元组添加权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319340/

相关文章:

c++ - 如何创建元组列表 C++

python - 橙色终端文本

python - 如何在 jupyter notebook 中获取已不存在的导入 .py 文件的源代码?

python - 关于 Glashammer App Engine Web 框架的观点

list - lisp 列表中对子集的组合

sharepoint - 在 SharePoint 中,创建自定义列表 'schema.xml' 文件的最简单方法是什么?

mysql - 如何在 MySQL Python 中创建字典中的字典?

python - memory_profiler 的 mprof 未运行

c# - 查明字符串列表项是否以另一个列表中的另一个项目开头

python - 为什么由不同初始化的集合构成的元组是相等的?