简体   繁体   中英

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?

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.

Your issue: convert a list of strings into a list of integers, where the same strings should become the same integers (whatever those integer are)

The method index("value") of a list returns the first index where "value" is found. For all the identical strings "value" in the list, this method will return the same integer.

>>> 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']

>>> my_list.index('This is a string')
0

>>> indexes=[my_list.index(l) for l in my_list]
>>> print(indexes)
[0, 0, 2, 3, 0, 5]
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']

converter = {}
i = 1

for item in my_list:
    if item not in converter:
        converter[item] = i
        i += 1

int_list = [converter[i] for i in my_list]

You want to make a list by applying a function to all members of another list. This is a list comprehension.

l1 = ['1', '2', '3', '4', '5', '6']
l2 = [int(x) for x in l1]
print l2

[1, 2, 3, 4, 5, 6]

Of course, you have some completely different function in mind, and I have no idea how you got those numbers from those strings, but I assume it is irrelevant. List comprehension will use whatever function you want.

l1 = ['string', 'this', 'is']
def f(s):
    return len(s)
l2 = [f(x) for x in l1]
print l2

[6, 4, 2]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM