I want to compare two lists. In python, each element of a list can be a different data type.
Suppose I have the two following lists:
import numpy as np
x = [1, 2.5, 'a string', ['a', 'b'], [5, 5.5]]
y = [1, 2.5+1e-8, 'a string', ['a', 'b'], [5, 5.5+1e-8]]
x_no_float = [1, 'a string', ['a', 'b'], [5]]
y_no_float = [1, 'a string', ['a', 'b'], [5]]
If you first look at x
and y
only. Both lists contain int, float, str, list of str, list of numbers (int and float). The difference between list x
and list y
is there are two floats, which has 1e-8
in list y
. In this case, x
and y
should be tested as almost equal.
I am using np.testing
framework.
-
To assert lists of only float numbers,
assert_allclose
can be used:np.testing.assert_allclose([2.5, 5.5], [2.5+1e-8, 5.5+1e-8])
-
If no float is there, then
assert_equal
can be used:np.testing.assert_equal(x_no_float, y_no_float)
In my practical case, I do not know whether there are floats in the list or not. Can you please show me how to write a proper test for it? Moreover, there can be a large number of elements in the lists, so explicit for-loop(s) might not be an elegant/efficient solution.
Thanks.
Aucun commentaire:
Enregistrer un commentaire