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

标签 python list tuples similarity

我有以下列表:

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

关于python - 检查 Python 元组中元素之间的相似性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42557033/

相关文章:

python - 追加函数嵌套在 IF 语句主体中不起作用

C++0x : iterating through a tuple with a function

python - 如何在python 3中更改或禁用tkinter消息框的默认声音

python - 学生选课组织表

python - 按另外两个列表对 Python 中的列表进行排序

java - 从各种类型的返回值创建列表

c# - IEnumerable 的可能多重枚举 - 如果我想要多重枚举怎么办?

c++ - 给定 std::tuple<T...> 时可变参数模板类的实例化?

json - 在 Swift 中处理 json 中不同类型的元组

python - LSTM 和 CNN 结合存在问题吗? (Python、喀拉斯)