python - 比较向量列表
问题描述
我需要比较两个向量列表并取它们相等的元素,例如:
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]
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)
推荐阅读
- php - 如何为不同的用户组更改我的网站的 CSS 样式?
- dart - 有没有 *?飞镖中的操作员?
- azure-data-studio - 将 settings.json 移动到 Azure Data Studio 的其他文件夹
- amazon-redshift - Redshift 警报 - HealthStatus 和 MaintenanceMode 复合
- java - 第一行中的eclipse java代码注释文本
- c# - left join linq 与 where 子句
- database - 第三范式 (3NF)
- clojure - 练习 Clojure 练习
- javascript - 如何在错误和退出后保持 Golang WebAssembly 实例运行(代码:2)
- javascript - 强制 IFrame 加载网站的移动版本