I have this unicode string .
u"[(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]"
<type 'unicode'>
how can i convert it to two separate list
I have this unicode string .
u"[(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]"
<type 'unicode'>
how can i convert it to two separate list
What you showed is a list, but you said you had a string. So assuming you really do have a string, you can use eval()
to turn it into a list and then do an inverse zip()
to get your values into two tuples (which can be easily converted into lists):
s = u"[(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]"
type(s)
#<type 'unicode'>
l1, l2 = zip(*(eval(s)))
print(l1)
#(2102, 1882, 1304, 577, 470)
print(l2)
#('a', 'b', 'c', 'd', 'e')
You could use two list comprehensions:
ex = [(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]
list1 = [x[0] for x in ex]
list2 = [x[1] for x in ex]
you can also try
unicode_list =[(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]
map(list,zip(*unicode_list))
where zip() in conjunction with the * operator can be used to unzip a list.