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.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With