da1g
da1g

Reputation: 117

Making an array from values of a 2D array

Confusing title, not sure how to formulate myself. Example at the end, probably makes it easier to understand.

So, I have an array A_Main1 where each element is another array, A_Elem0, A_Elem1...A_ElemN

I want to make a new array where each element is the first element of every array A_ElemI in A_Main1

I've seen code of this before but can't remember how it's done. This is what part of my code looks like

latitudeInfo = [latitude1Info[], latitude2Info[]...latitudeNInfo[]]
#latitudeXInfo[0] = the actual latitude, latitudeXInfo[>0] are values in someway 
#connected to the latitude. So the 0th element of latitudeXInfo is always the latitude

I want to make a new array of all latitudes in latitudeInfo

possibleLatitudes = []
possibleLatitudes.append(latitudeInfo[i][0] for i in latitudeInfo)

Thinking that possibleLatitudes appends the 0th element of the i:th list in latitudeInfo but this doesn't seem to work.

Upvotes: 1

Views: 37

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20414

You can use a list-comprehension that iterates through each list in latitudeInfo and takes the first element from that list with l[0].

possibleLatitudes = [l[0] for l in latitudeInfo]

Note that you are actually using lists here, and not arrays. This is a common misconception for people learning Python - especially coming from other languages. Basically the only time you use arrays in Python is with the numpy module. Everything else with square brackets [] is normally a list.

Upvotes: 3

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

You can use map in python like below. https://docs.python.org/3/library/functions.html#map. It is similar to map in Javascript, Ruby or any other language.

lambda is an anonymous function that returns the specified criteria. http://www.secnetix.de/olli/Python/lambda_functions.hawk

lats = list(map(lambda l: l[0], latitudeInfo))

EXAMPLE

>>> k = [[1, 2], [3, 4], [5, 6]]
>>> list(map(lambda i: i[0], k))
[1, 3, 5]

Upvotes: 0

Related Questions