aty aty - 3 months ago 9
Python Question

Python: Can this be done in a single list comprehension statement

What I am trying to do is extracting zeroth element in a list and first element in another list of the given 2 dimensional list.

baseball = [[180, 78.4],
[215, 102.7],
[210, 98.5],
[188, 75.2]]

x = [ a[0] for a in baseball ]
y = [ a[1] for a in baseball ]
print x
print y


Can this be done in a single list comprehension statement?

Answer

Assuming it's rectangular (ie. the length of the inner lists is consistent), you can implement the following:

def transpose(matrix):
    return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

Then, your problem is just a call to transpose (x, y = transpose(baseball)).

Comments