1

How do I convert a column in a matrix to a list in Python? E.g. convert

test = [['Student','Ex1','Ex2','Ex3'],['Thorny','100','90','80'],['Mac','100','90','80'],['Farva','100','90','80']]

to

Student = ['Thorny','Mac','Farva']

Please advise.

Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
aseem puri
  • 61
  • 1
  • 7

3 Answers3

2

Try this, the most compact way I could come up with: Student = [y[0] for y in test]

The 0 can be changed to what you want of course.

Stepan Filonov
  • 324
  • 1
  • 11
1

Easiest way is to use numpy for its indexing:

import numpy as np
convert_test = [['Student','Ex1','Ex2','Ex3'],['Thorny','100','90','80'],['Mac','100','90','80'],['Farva','100','90','80']]
convert_test = np.array(convert_test)
print(convert_test[:,0])

array(['Student', 'Thorny', 'Mac', 'Farva'], dtype='U7')

campellcl
  • 182
  • 2
  • 14
0
Student = list(zip(*test))[0][1:]

where 

>>>list(zip(*test))

[('Student', 'Thorny', 'Mac', 'Farva'),
 ('Ex1', '100', '100', '100'),
 ('Ex2', '90', '90', '90'),
 ('Ex3', '80', '80', '80')]
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
  • 3
    While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. Please edit your answer. – hellow Aug 28 '18 at 06:33
  • Also, raw code snippets may be identified as "low quality posts" and deleted. I'm seeing this post from that queue. – Zev Aug 28 '18 at 18:46