将数据添加到 Python 中的嵌套列表

Adding data to nested lists in Python

我正在尝试为我的网站图库构建一个嵌套列表。我从数据库中提取数据并将其插入到列表中,然后我的图库页面将列表中的元素添加到我的网页中。

我的列表是:

gallery = [[], [[]]]

对于gallery[0]中的每个元素,它包含所有年份,在gallery[1]中有一个对应的列表,每个列表包含存储所有照片名称,事件,日期的列表等。我遇到的问题是,当我遍历我的列表时,gallery[1] 中的每个子列表中都有相同的照片名称,即使每个子列表的日期都是唯一的。

添加照片的循环:

images = db.session.query(Gallery.image_file_th, Gallery.image_file_fl, Gallery.date).order_by(Gallery.image_order)
    for y in gallery[0]: # LOOP THROUGH THE YEARS
        for x in range(len(gallery[1])):
            for w in range(len(gallery[1][x])): # LOOP THROUGH LIST CORRESPONDING TO YEARS
                for pic in images: # LOOP THROUGH EACH IMAGE NAME PULLED FROM THE DATABASE
                    if str(pic.date) == str(gallery[1][x][w][0]):
                        gallery[1][x][w][2].append(pic.image_file_fl)
                        gallery[1][x][w][3].append(pic.image_file_th)
                    else:
                        pass

我将照片附加到索引 2 和 3 的子列表中包含的列表。

示例库列表:

gallery = [[2019], [[
        [date_of_event, event_name, [list_of_thumbnails], [list_of_photos]]
    ]]]

为什么两个子列表中出现相同的照片?如果需要,我很乐意提供更多信息。

感谢@0x5453 和@JChao 关于使用字典而不是嵌套列表的建议。

for 循环的问题是我用相同的变量声明了每个列表:

gallery[key_year].append(
                    {
                        'date': y.date,
                        'title': y.event,
                        'fulls': fulls, # declared as fulls = []
                        'thumbs': thumbs, # declared as thumbs = []
                        'date_parsed': y.date.strftime('%A, %b %-d'),
                        'id': ide
                    }
                )

这导致了问题中描述的问题。

解决方法:

gallery[key_year].append(
                    {
                        'date': y.date,
                        'title': y.event,
                        'fulls': [],
                        'thumbs': [],
                        'date_parsed': y.date.strftime('%A, %b %-d'),
                        'id': ide
                    }
                )