首页 > 解决方案 > 比较向量列表

问题描述

我需要比较两个向量列表并取它们相等的元素,例如:

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:元素的顺序无关紧要

而且,如果可能的话,我只想在比较中考虑到小数点后第二位,而不是四舍五入或缩短它们。可能吗 ?提前谢谢!

标签: pythonvectorblender

解决方案


# 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在这种情况下,如果只有四舍五入的条目相等,我们就会选择 的条目。否则最后一行需要调整。

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

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

注意: round可能有问题,应该在当前的 Python 版本中解决。不过,使用字符串可能会更好:

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)

推荐阅读