Ad

Python : How To Make 1-D Array From 2-D Array

- 1 answer

I have array2D = [[1,2,3],[4,5,6]]. What I want is a function which takes an index and returns the elements in 1D array.

Example: fn(0) -> returns [1,4]
         fn{1) -> returns [2,5]

I need a fast way to do this.

Ad

Answer

you can use lambda and list comprehension:

array2D = [[1,2,3],[4,5,6]]

fn = lambda x: [item[x] for item in array2D]

print(fn(0)) # [1, 4]
print(fn(1)) # [2, 5]
print(fn(2)) # [3, 6]

as suggested in the comments, you may apply the same concept with a function definition:

def fn(x): return [item[x] for item in array2D]

print(fn(0)) # [1, 4]
print(fn(1)) # [2, 5]
print(fn(2)) # [3, 6]

Lambda functions are pretty useful, and let you define operation in a really clear way.
In our example, our lambda accept a variable x, which represent the index we want of each item in array2D

Then you have list comprehension, similarly to lambda function, they are a really powerful tool and a must in python

In this situation you should prefear the function definiton, as suggested by PEP-8.

Ad
source: stackoverflow.com
Ad