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.
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.
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.
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')
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')]