compare vector lists

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-02 13:23:49

问题


I need to compare two list of vectors and take their equal elements, like:

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: 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!


回答1:


# 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]

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])

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)


来源:https://stackoverflow.com/questions/59106106/compare-vector-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!