Python append lists into lists

2019-09-06 19:01发布

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.

4条回答
走好不送
2楼-- · 2019-09-06 19:46

Try this:

locations = [[]]
row = locations[0]
row.append([x, y])
查看更多
贪生不怕死
3楼-- · 2019-09-06 19:47

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]]
查看更多
【Aperson】
4楼-- · 2019-09-06 19:49

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)
查看更多
可以哭但决不认输i
5楼-- · 2019-09-06 19:52

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]]]
查看更多
登录 后发表回答