If you want to retrieve multiple values from a list in Python, you can retrieve them in slices if they are contiguous, but I didn't know how to retrieve them if they were not contiguous, so I looked it up.
It seems that ʻitemgetter` can be used from python2.5 or later, so I will try using it. If you pass an index in the list, the value of that index will be returned.
from operator import itemgetter
a = ("a", "b", "c", "d", "e")
print itemgetter(1,3)(a) # ('b', 'd')
The reason why I wanted to do this is that it would be nice if the label was returned by machine learning, but when extracting the original data from it, I couldn't think of an easy way to write it. For example, in a classifier that distinguishes between lowercase and uppercase letters, if a label is returned and only uppercase letters are extracted from it, I wrote as follows.
from operator import itemgetter
import numpy
label_prediction = numpy.array([0,0,1,1,0,1])
data = ["a","b","C","D","e","F"]
label_match = numpy.where(label_prediction==1)[0]
print itemgetter(*label_match)(data)
Please let me know if there is another good way.
I learned from s-wakaba! Thank you very much. I was pessimistic that I couldn't use numpy if it was a character string, but I could use it normally. Much more beautiful than using itemgetter.
import numpy
label_prediction = numpy.array([0,0,1,1,0,1])
data = ["a","b","C","D","e","F"]
print numpy.array(data)[label_prediction==1]
It would be helpful if you could tell me a better way to write down what you researched. I would like to take notes and expose my ignorance.
Recommended Posts