繁体   English   中英

检查元组Python中元素之间的相似性

[英]Check similarity between elements in tuple Python

我有以下清单:

list= [(12.947999999999979,5804),(100000.0,1516),(12.948000000000008,844),(12.948000000000036,172),(18.252000000000066,92)]

元组中的第一个元素代表值,而元组的第二个元素代表此值出现在文档中的频率。 我的问题是如何将列表的相似元素(例如列表的第一个元素和第三个元素)聚集在一起并组合它们的频率?

使用Counter元素并将round()为所需的小数位数。 顺便说一句,不要使用保留字list

from collections import Counter

l= [(12.947999999999979,5804),(100000.0,1516),(12.948000000000008,844),(12.948000000000036,172),(18.252000000000066,92)]
precision = 3

c = Counter()

for value, times in l:
    c.update([round(value, precision)]*times)

如果您已经将数据保存在计数器中,则可以直接执行以下操作:

from collections import Counter

# data = Counter()  # This is the counter where you have the data
precision = 3

joined = Counter()

for value, times in data.items():
    joined.update([round(value, precision)]*times)

data = joined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM