【问题标题】:I want to create a list of lists我想创建一个列表列表
【发布时间】:2021-01-14 23:07:22
【问题描述】:

我知道在 stackoverflow 上有很多类似的问题,但它们似乎并没有解决我的问题。如果您查看下面的代码,您可以看到我正在创建一个名为“tempAdList”的临时广告列表,并且当 if 条件评估为真时,我正在创建一个名为“ad_list”的列表列表。我要附加到“ad_list”,所以我希望每次“if 语句”评估为 true 时,都会将 4 个广告的新列表附加到“ad_list”,但无论出于何种原因,我得到的输出低于我正在寻找的输出。我在这里做错了什么?

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)

输出:

【问题讨论】:

  • 请提供示例输入或运行案例以及所需的输出。
  • 请查看link你会发现这个问题已经得到解答

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


【解决方案1】:

如果您只想要一个列表列表,其中内部列表有 4 个元素。 你可以试试这样的:

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

【讨论】:

    【解决方案2】:

    在列表上使用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=[]替换tempAdList.clear()

    【讨论】:

      【解决方案3】:

      每次您执行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))
      

      【讨论】:

        猜你喜欢
        • 2018-09-18
        • 2018-07-30
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        相关资源
        最近更新 更多