1

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

pault
  • 37,170
  • 13
  • 92
  • 132
Rohit Kumar
  • 549
  • 2
  • 8
  • 20

3 Answers3

3

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')
pault
  • 37,170
  • 13
  • 92
  • 132
0

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]
Blazina
  • 988
  • 8
  • 12
  • This is the output i'm getting when printing first list., [u'[', u'(', u'2', u'1', u'0', u'2', u',', u' ', u"'", u'a'.................. – Rohit Kumar Feb 09 '18 at 15:36
  • if you run the above example I provided it should return two lists as you asking, but it seems you're example above wasn't correctly entered and should been shown as `u"[(2102, 'a'), (1882, 'b'), (1304, 'c'), (577, 'd'), (470, 'e')]"` as in the response from @pault below, and thus that answer would be the right way of doing what you desire. – Blazina Feb 09 '18 at 15:49
0

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.

Matt. Stroh
  • 856
  • 7
  • 16