2

I am trying to write a function that goes through a matrix. When a criteria is met, it remembers the location.

I start with an empty list:

locations = []

As the function goes through the rows, I append the coordinates using:

locations.append(x)
locations.append(y)

At the end of the function the list looks like so:

locations = [xyxyxyxyxyxy]

My question is:

Using append, is it possible to make the list so it follows this format:

locations = [[[xy][xy][xy]][[xy][xy][xy]]]

where the first bracket symbolizes the locations of a row in the matrix and each location is in it's own bracket within the row?

In this example the first bracket is the first row with a total of 3 coordinates, then a second bracket symbolizing the 2nd row with another 3 coordinates.

1
  • I did not downvote, but you might be missing a few commas. Commented Oct 29, 2013 at 16:40

5 Answers 5

7

Instead of

locations.append(x)

You can do

locations.append([x])

This will append a list containing x.

So to do what you want build up the list you want to add, then append that list (rather than just appending the values). Something like:

 ##Some loop to go through rows
    row = []
    ##Some loop structure
        row.append([x,y])
    locations.append(row)
Sign up to request clarification or add additional context in comments.

1 Comment

I found this to be the easiest solution. Thanks for you help!
3

simple example

locations = []

for x in range(3):
    row = []
    for y in range(3):
        row.append([x,y])
    locations.append(row)

print locations

result:

[[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]]]

Comments

2

Try something like:

def f(n_rows, n_cols):
    locations = [] # Empty list
    for row in range(n_rows):
        locations.append([]) # 'Create' new row
        for col in range(n_cols):
            locations[row].append([x, y])
    return locations

Test

n_rows = 3
n_cols = 3
locations = f(n_rows, n_cols)
for e in locations:
    print
    print e

>>> 

[[0, 0], [0, 1], [0, 2]]

[[1, 0], [1, 1], [1, 2]]

[[2, 0], [2, 1], [2, 2]]

Comments

1

Try this:

locations = [[]]
row = locations[0]
row.append([x, y])

Comments

0

If you don't go through a matrix and just want to embed some lists on a list:

groupA = [1,2,3]
groupB = ['a','b','c']
pair = []
for x in range(3):
    pair.append([groupA[x],groupB[x]])

>>>:
[[1, 'a'], [2, 'b'], [3, 'c']]

Comments

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.