Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map unique strings to integers in Python [duplicate]

Tags:

python

I have a list, let say L = ['apple','bat','apple','car','pet','bat'].

I want to convert it into Lnew = [ 1,2,1,3,4,2].

Every unique string is associated with a number.

I have a java solution using hashmap, but I don't know how to use hashmap in python. Please help.

like image 955
BuggerNot Avatar asked Apr 04 '17 09:04

BuggerNot


2 Answers

x = list(set(L))
dic = dict(zip(x, list(range(1,len(x)+1))))

>>> [dic[v] for v in L]
[1, 2, 1, 3, 4, 2]
like image 139
Colonel Beauvel Avatar answered Sep 20 '22 12:09

Colonel Beauvel


Here's a quick solution:

l = ['apple','bat','apple','car','pet','bat']

Create a dict that maps all unique strings to integers:

d = dict([(y,x+1) for x,y in enumerate(sorted(set(l)))])

Map each string in the original list to its respective integer:

print [d[x] for x in l]
# [1, 2, 1, 3, 4, 2]
like image 26
acidtobi Avatar answered Sep 21 '22 12:09

acidtobi