0

I would like to separate the following tuple into two lists

(('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), 
 ('fear', 25.071))

I want my lists to look like the following:

a = ('happy', 'neutral', 'neutral', 'happy', 'fear')
b = (5.001, 10.004, 15.006, 20.071, 25.071)

The split() method is not working on this.

martineau
  • 119,623
  • 25
  • 170
  • 301
shasha0607
  • 123
  • 1
  • 9

4 Answers4

4

Here comes your new hero, the zip function!

l = (('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), ('fear', 25.071))
a, b = zip(*l)

For future usages, we could say that it works in two different modes:

  • zip(*iterable) generates n iterables (being n the size of every tuple in the iterable), where every iterable contains the ith element of each tuple (the example of my answer).
  • zip(iterable_1, ..., iterable_n) generates a single iterable where every element is a tuple of size n containing the element of every iterable at the corresponding index.
josepdecid
  • 1,737
  • 14
  • 25
0
t = (('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), ('fear', 25.071))
a = [x[0] for x in t]
b = [x[1] for x in t]

This uses list comprehension to address the problem. It creates list 'a' using first element(index 0) from each tuple in 't' while creates list 'b' using the second element(index 1).

Aditya.B
  • 21
  • 3
0
t = (('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), ('fear', 25.071))
a, b = zip(*t)
Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31
0

to do what you want you can just do the following

c = (('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), ('fear', 25.071))
a, b = zip(*c)

but in this case a and b are tuples not lists, lists are in this format :

a = ['happy', 'neutral', 'neutral', 'happy', 'fear']
b = [5.001, 10.004, 15.006, 20.071, 25.071]

you can just do list(a) to convert from tuple to list

Walid Sliti
  • 109
  • 2
  • 10