Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - Convert list of strings to list of integers?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...