Reputation: 39
If I have the following matrix:
m = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
how do I return a list that looks like this
[[1, 4, 7],
[2, 5, 8],
[3, 6, 9]]
without using built-in functions?
Edit: I can use len() and range()
Upvotes: 0
Views: 67
Reputation: 61920
Weird approach:
m = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
res = map(lambda *args: args, *m)
print(list(res))
Output
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If list are required:
res = list(map(lambda *args: list(args), *m))
print(res)
Alternative:
res = [*map(lambda *args: list(args), *m)]
Upvotes: 1
Reputation: 316
try this
m = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
result=[[0 for i in range(len(m))] for j in range(len(m[0]))]
for i in range(len(m)):
for j in range(len(m[0])):
result[j][i]=m[i][j]
print(result)
Upvotes: 0
Reputation: 73490
You can use a nested comprehension, à la:
[[row[i] for row in m] for i in range(len(m[0]))]
If the typical transpositioning idiom zip(*m)
(or [*map(list, zip(*m))]
if exact types matter) is to be avoided as too purpose-built.
Upvotes: 2