我想创建一个列表列表

时间:2020-09-29 10:37:09

标签: python python-3.x django django-models

我知道关于stackoverflow的问题很多,但它们似乎并不能解决我的问题。如果您在下面查看我的代码,则可以看到我正在创建一个称为“ tempAdList”的广告的临时列表,如果条件为true,则将创建一个名为“ ad_list”的列表。我要附加到“ ad_list”上,因此我希望每次“ if语句”评估为true时,都会在“ ad_list”上附加一个新的4个广告列表,但是出于任何原因,我都会得到以下输出,这不是我想要的。我在这里做什么错了?

ads = Advert.objects.all()

counter = 1
tempAdList = []
ad_list = []

for i, ad in enumerate(ads):
    tempAdList.append(ad)
    if counter == 4:
        # print(tempAdList)
        ad_list.append(tempAdList)
        print(ad_list)
        tempAdList.clear()
        counter = 0
    counter += 1

    adsNum = len(ads)
    # print("i = {} and adsNum = {}".format(i, adsNum))
    if i == adsNum -1 and adsNum % 4 != 0:
        ad_list.append(tempAdList)

输出:enter image description here

3 个答案:

答案 0 :(得分:0)

如果您只想要一个列表列表,则内部列表包含4个元素。 您可以尝试:

new_list = [ads[i:i+4] for i in range(0, len(ads), 4)] 

答案 1 :(得分:0)

在列表上使用clear方法也会影响对其的所有引用,例如

>>a = [1, 2, 3]
>>b = a
>>a.clear()
>>print('a =',a)
a = []
>>print('b =',b)
b = []

因此,您在ad_list.append(tempAdList)中所做的就是向ad_list重复添加对同一对象的引用,即,每次更新tempAdList时,对每个对象都进行相同的更新参考。您真正想做的是用一个新对象重置tempAdList,所以用tempAdList.clear()替换tempAdList=[]

答案 2 :(得分:0)

每次执行tempAdlist.clear()时,都会清除列表中的所有元素。但是因为您将列表附加到ad_list,所以您基本上也将其清除了。这样您的清单就少了。这是由于引用而不是重新创建列表的性质。您想要的是在添加时从tempAdlist创建列表,如下所示:ad_list.append(list(tempAdlist))这样,它将是tempAdlist中的一个全新列表。本质上,您的代码变为:

ads = Advert.objects.all()

counter = 1
tempAdList = []
ad_list = []

for i, ad in enumerate(ads):
    tempAdList.append(ad)
    if counter == 4:
        # print(tempAdList)
        ad_list.append(list(tempAdList))
        print(ad_list)
        tempAdList.clear()
        counter = 0
    counter += 1

    adsNum = len(ads)
    # print("i = {} and adsNum = {}".format(i, adsNum))
    if i == adsNum -1 and adsNum % 4 != 0:
        ad_list.append(list(tempAdList))