1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]

1 Comment

You neither need lambda nor map for this task. In general list comprehensions should be preferred rather functional programming` methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.