Can anyone tell me how to fix the following code? np.where should return index 0.
import numpy as np
listoftups=[("a", "b"), ("n"), ("c","d","e"), ("f", "g")]
np.where(listoftups==("a", "b"))
np.where(('a','b') in listoftups)
What you have in your code returns false
>>> listoftups==("a", "b")
False
Where as,
>>> ('a','b') in listoftups
True
Assuming that you are trying to find the index of the tuple. Here is a solution which doesn't require numpy.
listoftups=[("a", "b"), ("n"), ("c","d","e"), ("f", "g")]
search_tuple = ("a", "b")
print(listoftups.index(search_tuple))
Will return 0
search_tuple = ("f", "g")
print(listoftups.index(search_tuple))
Will return 3
Here is how to force numpy to do what you want:
listoftups=[("a", "b"), ("n"), ("c","d","e"), ("f", "g")]
where
operates on boolean arrays, a comparison like a==b will create a boolean array if a or b is a numpy array but not if both are native python objects. Let's also create an example with two occurrences of the search tuple. .
arroftups = np.array(listoftups)
twice = np.concatenate(2*[listoftups])
.
probe = np.empty((),object)
probe[()] = "a", "b"
.
np.where(arroftups==probe)
# (array([0]),)
np.where(twice==probe)
# (array([0, 4]),)
Note if you are sure there is exactly one occurrence of the test tuple, then @Watchdog101's solution is probably better. But it will not work in the general case.
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.