Python将列表追加到列表中 [英] Python append lists into lists

查看:978
本文介绍了Python将列表追加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个通过矩阵的函数.符合条件时,它会记住位置.

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

我从一个空列表开始:

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]

我的问题是:

使用附加项,是否可以使列表遵循以下格式:

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

第一个括号代表矩阵中一行的位置,而每个位置都位于该行中它自己的括号中?

在此示例中,第一个括号是第一行,共有3个坐标,然后是第二个括号,表示第二行具有另外3个坐标.

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.

推荐答案

代替

locations.append(x)

您可以

locations.append([x])

这将追加一个包含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)

这篇关于Python将列表追加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆