For instance I have this list:
A = [(1, 2.5), (2, 5.0), (3, 7.5), (4, 10.0)]
and I have another list with the following entry:
B = [2.5, 7.5, 12.5]
What I want is a program in Python where if the 2nd element of each tuple in A
, namely 2.5
, 5.0
, 7.5
, and 10.0
, can be found in B
, it will create another variable which looks like this:
C = [(1, 2.5), (3, 7.5)]
where it removes the other tuples in A
whose 2nd elements are not in B
. I tried to code it this way:
A = [(1, 2.5), (2, 5.0), (3, 7.5), (4, 10.0)]
D = np.asarray(list(A))
E = []
if D[:, 1] in B:
E = np.append(E,D)
else:
pass
but I got an error of:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Why not simply the following:
>>> A = [(1,2.5), (2,5.0), (3,7.5), (4,10.0)]
>>> B = [2.5, 7,5, 12.5]
>>> C = [a for a in A if a[1] in B]
>>> C
[(1, 2.5), (3, 7.5)]
You could use np.n1d to determine which values in A[:, 1]
are also in B
:
In [104]: A = np.array([(1,2.5), (2,5.0), (3,7.5), (4,10.0)])
In [105]: B = [2.5, 7.5, 12.5]
In [106]: mask = np.in1d(A[:, 1], B)
In [107]: mask
Out[107]: array([ True, False, True, False], dtype=bool)
In [108]: A[mask]
Out[108]:
array([[ 1. , 2.5],
[ 3. , 7.5]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.