在列表中查找元素的索引,该元素大致等于另一个列表中的元素
我有2个带有浮点数的列表:
list_1 = [1.03, 3.56, 4.91, 2.85, 5.55, 1.12, 1.73, 1.33, 2.56, 2.58, 3.53]
list_2 = [1.05, 1.55, 2.05, 2.55, 3, 3.55, 4]
目标是比较2个列表,并根据特定的阈值近似相等,从第一个列表返回元素的索引(List_1
)。
def compare_lists(list1, list2, threshold=0.02):
output_list = []
for i in range(len(list1)):
for j in range(len(list2)):
print(abs(list1[i] - list2[j]))
if abs(list1[i] - list2[j]) <= threshold:
output_list.append(i)
return output_list
这仅是返回[1,8]
我认为这是错误的。输出列表中应包含一些索引,例如0和最后一个。
我认为问题是浮点的减法。我检查了1.03和1.05之间的差异,并返回0.02000000000000018
我如何解决此问题?或者我只是可以围绕它们,但这不是一个不错的选择,因为列表可以包含多种小数点。它不仅范围2分,也不是阈值。
I have 2 lists with floating point numbers:
list_1 = [1.03, 3.56, 4.91, 2.85, 5.55, 1.12, 1.73, 1.33, 2.56, 2.58, 3.53]
list_2 = [1.05, 1.55, 2.05, 2.55, 3, 3.55, 4]
The goal is to compare 2 lists and return the indexes of element from the first list (list_1
) if they are approximatly equal based on the specific threshold.
def compare_lists(list1, list2, threshold=0.02):
output_list = []
for i in range(len(list1)):
for j in range(len(list2)):
print(abs(list1[i] - list2[j]))
if abs(list1[i] - list2[j]) <= threshold:
output_list.append(i)
return output_list
This is only return [1, 8]
that I think it is wrong. There are some indexes should be included in the output list such as 0 and the last one.
I think the problem is the subtraction of the floating points. I checked the difference between 1.03 and 1.05 and it returns 0.02000000000000018
How can I fix this problem? or I just could round them, but this is not a good choice because the list can contain varied decimal points. It doesn't scope just 2 points, as well as the threshold.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于圆形错误,您可能需要更多的填充:
You might want to have more padding, due to round-off error:
Python具有
DECIMAL
模块 https://docs.python。 org/3/library/decimal.html “用于快速正确的小数浮点算术算术”。Python has the
decimal
module https://docs.python.org/3/library/decimal.html "for fast correctly-rounded decimal floating point arithmetic".