比较矢量列表
compare vector lists
我需要比较两个向量列表并取其相等的元素,例如:
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:元素的顺序无关紧要!
还有,如果可能的话我想在比较中只考虑到小数点后第二位
但没有四舍五入或缩短它们。可能吗 ?
提前致谢!
# 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]
在这种情况下,如果只有四舍五入的条目相等,我们 select veclist1
的条目。否则最后一行需要调整。
如果需要所有原始元素,则可以使用两个原始列表计算最终列表:
equalelements = ([veclist1[veclist1_rounded.index(el)] for el in slct_rounded]
+ [veclist2[veclist2_rounded.index(el)] for el in slct_rounded])
注意: round
在当前 Python 版本中可能有 issues, which should be solved。不过,使用字符串可能会更好:
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)
我需要比较两个向量列表并取其相等的元素,例如:
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:元素的顺序无关紧要!
还有,如果可能的话我想在比较中只考虑到小数点后第二位 但没有四舍五入或缩短它们。可能吗 ? 提前致谢!
# 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]
在这种情况下,如果只有四舍五入的条目相等,我们 select veclist1
的条目。否则最后一行需要调整。
如果需要所有原始元素,则可以使用两个原始列表计算最终列表:
equalelements = ([veclist1[veclist1_rounded.index(el)] for el in slct_rounded]
+ [veclist2[veclist2_rounded.index(el)] for el in slct_rounded])
注意: round
在当前 Python 版本中可能有 issues, which should be solved。不过,使用字符串可能会更好:
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)