首页 > 解决方案 > 如何获取一个列表并将每个元素附加到一个新列表中,具体取决于它的位置?

问题描述

所以我通过 for 循环创建的第一个列表如下所示

["1variable1", "1variable2", "1variable3", "1variable4", "1variable5"].

然后我希望根据他们的位置将它附加到新列表中。

so List1 will be [1variable1]
List2 will be [1variable2]
etc

然后循环的下一步将创建另一个

["2variable1", "2variable2", "2variable3", "2variable4", "2variable5"]

然后我想将它附加到上一个列表中;

List1 will be [1variable1, 1variable2]
List2 will be [1variable2, 2variable2]
etc.

目前我有它,所以它只是使用方括号来拉出列表的每个部分,但我不知道如何循环使用它,也许下次我运行它时会有超过 4 个条目,我将错过第 5 次。

lst1 = [item[0] for item in Genres]
lst2 = [i[1] if len(i) > 1 else '' for i in Genres]
lst3 = [i[2] if len(i) > 2 else '' for i in Genres]
lst4 = [i[3] if len(i) > 3 else '' for i in Genres]
lst5 = [i[4] if len(i) > 4 else '' for i in Genres]

如果下一个列表没有前一个列表那么多,那么它应该填写一个空格,因为它们都需要在同一个位置

列表创建如下;

my_list = my_list[1:]
length = len(my_list)
my_list =  my_list[0:3]
for film in my_list:
    filmIndex = my_list.index(film) + 1
    query = film + " imdb"
    for j in search(query, tld="co.in", num=10, stop=1, pause=2):
        page = requests.get(j)
        response = page.status_code
        if response == 200:
            soup = BeautifulSoup(page.content, "lxml")
            genreData = soup.find_all("div",{"class":"subtext"})

然后

            for h in genreData:
                a = h.find_all('a')
                aLength = len(a)
                a1 = a[0]
                for b in range(0,aLength - 1):
                    r = a[b].string
                    genres.append(r)

然后,我想将每种类型添加到单独的列中,类型 1、类型 2 等,直到最大值有多少。显然,如果最大值为 4 并且一部电影只有 1 则其中一些为 NULL 然后为每部电影创建该电影所有类型的列表,我想将它们放入单独的列中

标签: python

解决方案


一种可能的方法是创建列表列表。

创建列表列表允许您遍历列表以将每个变量插入并放置到变量索引处的列表中。当然,如果你有一个大列表或正在做你的第一次通过,你会遇到一个你还没有遇到过的索引,所以你需要在那个索引处初始化一个空列表。

list1 = ["1variable1", "1variable2", "1variable3", "1variable4", "1variable5"]
list2 = ["2variable1", "2variable2", "2variable3", "2variable4", "2variable5"]

biglist = []

#insert list1
#this for loop can be repeated for every list you want to enter - maybe 
#put those into a list of lists, too?
for i in range(0, len(list1)):
  #check to see if there's a list in this entry
  if 0 <= i < len(biglist):
    #there's already a list here, add this to it
    biglist[i].append(list1[i])
  else:
    #there's no list here yet, create one and add its first variable
    biglist.append([])
    biglist[i].append(list1[i])

#repeat for the second list, and so on - you can nest these
for i in range(0, len(list2)):
  if 0 <= i < len(biglist):
    biglist[i].append(list2[i])
  else:
    biglist.append([])
    biglist[i].append(list2[i])

for l in biglist:
  print(l)

演示


推荐阅读