比较向量列表

2024-10-04 05:29:28 发布

您现在位置: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)]

观察:元素的顺序无关紧要!你知道吗

而且,如果可能的话,我只想考虑到比较中的第二个小数点 但不使它们变圆或变短。有可能吗? 提前谢谢!你知道吗


Tags: 元素列表顺序向量小数点变圆veclist1veclist2
1条回答
网友
1楼 · 发布于 2024-10-04 05:29:28
# 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可能有issues,在当前的Python版本中应该是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)

相关问题 更多 >