Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a list of strings that I want to convert to a simple integer array.

Example:

my_list = ['This is a string', 'This is a string', 'Hi! I am a string', 'I dislike strings', 'This is a string', 'Not a number']

Converted to:

[0, 0, 1, 2, 0, 3]

Elements in my_list that have the same value will all end up with the same integer in the converted array.

The idea behind this is that I want to utilize the following syntax (from matplotlib) to make a scatter chart, and it doesn't seem to like it when y_train or i is a string:

X_train_small_pca[y_train == i, 0]

How can I convert my list into integers, as above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

This should do:

>>> my_list = ['This is a string', 'This is a string', 'Hi! I am a string', 'I 
>>> dislike strings', 'This is a string', 'Not a number']
>>> mappedDict = dict(zip(set(my_list), xrange(len(my_list))))
>>> output = map(lambda x: mappedDict[x], my_list)
>>> output
[0, 0, 1, 2, 0, 3]

Explaining: You first remove duplicates in the list and map them with a single id (int in this case) into a dict. After that is as easy as transform each value in the list into the mapped id.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...