0

I've got a list which looks like this:

List = [('TestID', '2020-02-03 17:16:19.004125', '1'),
        ('TestID', '2020-02-03 17:16:20.893915', '2'),
        ('TestID', '2020-02-03 17:16:22.497974', '3'),
        ('TestID', '2020-02-03 17:16:23.785106', '4'),
        ('TestID', '2020-02-03 17:16:25.324855', '5'),
        ('TestID', '2020-02-03 17:16:26.985723', '6'),
        ('TestID', '2020-02-03 17:16:28.866707', '7'),
        ('TestID', '2020-02-03 17:16:30.477464', '8')]

I want to split this list into 3 lists which should look like this:

List1 = ['TestID', 'TestID', 'TestID', 'TestID`', 'TestID', 'TestID', 'TestID', 'TestID']
List2 = ['2020-02-03 17:16:19.004125', '2020-02-03 17:16:20.893915',
         '2020-02-03 17:16:22.497974', '2020-02-03 17:16:23.785106',
         '2020-02-03 17:16:25.324855', '2020-02-03 17:16:26.985723',
         '2020-02-03 17:16:28.866707', '2020-02-03 17:16:30.477464']
List3 = ['1', '2', '3', '4', '5', '6', '7', '8']

Can somebody tell me how I can do this in Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
L.Kaden
  • 27
  • 3

3 Answers3

3

You can use list comprehensions to index out of your subelements to create new lists.

>>> [i[0] for i in List]                        
['TestID', 'TestID', 'TestID', 'TestID', 'TestID', 'TestID', 'TestID', 'TestID']

>>> [i[1] for i in List]
['2020-02-03 17:16:19.004125', '2020-02-03 17:16:20.893915', '2020-02-03 17:16:22.497974', '2020-02-03 17:16:23.785106', '2020-02-03 17:16:25.324855', '2020-02-03 17:16:26.985723', '2020-02-03 17:16:28.866707', '2020-02-03 17:16:30.477464']

>>> [i[2] for i in List]                                    
['1', '2', '3', '4', '5', '6', '7', '8']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

You can use zip with unpacking here.

l1,l2,l3=zip(*List)

Note: l1,l2,l3 are tuples typecast them to list.

Or you can use map to convert them to list.

l1,l2,l3=map(list,zip(*List))
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0
L1=[]
for i in range(3):
    temp=[]
    temp=[j[i] for j in List]
    L1.append(temp)

You can access by indexing L1

Ojasv singh
  • 474
  • 8
  • 19