比较向量列表 [英] compare vector lists

查看:111
本文介绍了比较向量列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

veclist1 = [(0.453 , 0.232 , 0.870), (0.757 , 0.345 , 0.212), (0.989 , 0.232 , 0.543)]
veclist2 = [(0.464 , 0.578 , 0.870), (0.327 , 0.335 , 0.562), (0.757 , 0.345 , 0.212)]

equalelements = [(0.757 , 0.345 , 0.212)]


obs:元素无关紧要!的元素顺序

还有,如果可能的话我只想考虑直到比较中的小数点后第二位 但不舍入或缩短它们.是否有可能 ? 提前谢谢!


obs: The order of the elements don't matter!

And also, if possible I wanted to only consider till the 2nd decimal in the comparison but without rounding or shortening them. Is it possible ? Thx in advance!

推荐答案

# Get new lists with rounded values
veclist1_rounded = [tuple(round(val, 2) for val in vec) for vec in veclist1]
veclist2_rounded = [tuple(round(val, 2) for val in vec) for vec in veclist2]

# Convert to sets and calculate intersection (&)
slct_rounded = set(veclist1_rounded) & set(veclist2_rounded)

# Pick original elements from veclist1:
#   - get index of the element from the rounded list
#   - get original element from the original list
equalelements = [veclist1[veclist1_rounded.index(el)] for el in slct_rounded]

在这种情况下,如果仅四舍五入的条目相等,则选择veclist1的条目.否则,最后一行需要调整.

In this case we select the entries of veclist1 if only the rounded entries are equal. Otherwise the last line needs to be adjusted.

如果需要所有原始元素,则可以使用两个原始列表来计算最终列表:

If all original elements are needed, the final list can be calculated using both original lists:

equalelements = ([veclist1[veclist1_rounded.index(el)] for el in slct_rounded]
                 + [veclist2[veclist2_rounded.index(el)] for el in slct_rounded])

注意::round可能有问题,应在当前Python版本中已解决.不过,最好改用字符串:

Note: round might have issues, which should be solved in current Python version. Nevertheless, it might be better to use strings instead:

get_rounded = lambda veclist: [tuple(f'{val:.2f}' for val in vec) for vec in veclist]
veclist1_rounded, veclist2_rounded = get_rounded(veclist1), get_rounded(veclist2)

这篇关于比较向量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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