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

查看:37
本文介绍了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]

我的问题是:

使用append,是否可以使列表遵循这种格式:

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天全站免登陆