Python中的列表中有多个“ for”循环

时间:2019-03-14 05:34:53

标签: python for-loop arraylist nested-loops

这是我尝试过的代码:

booksa = [book[i] for book in books for k in range(len(lista)) for i in lista[k][0] ]
booksb = [book[j] for book in books for e in range(len(lista)) for j in lista[e][1] ]

嗨,我不太熟悉列表中的循环-列表理解。我有一个名为'books'的列表和一个名为'lista'的列表。我想在books中找到lista中每个元组的第二个元素,并将相应的对存储在列表booksabooksb中。

books = [(17,5), (3,55), (5,12), (14,9), (16,1), (9,5), (5,6), (18,13), (19,7), (1,20), (4,12), (11,1), (8,6), (8,18), (3,4), (13,7), (17,22), (20,7)]
lista = [[(0,9), (3,10), (6,15)]]

例如,对于(0,9)中的lista,我们回顾books并在17中找到(17,5)(0表示第一个元组),然后将17放入booksa,并将7(9表示第八元组)放入(9,5)

我该如何在列表中使用一些“ for”循环?

3 个答案:

答案 0 :(得分:2)

应用的逻辑如下:

  • 选择lista元组元素中的第一项,并使用它索引到books列表中,并获取存在的元组的第一项,以添加到booksa
  • 选择lista元组元素中的第二项,并使用它索引到books列表中,并获取存在的元组的第二项,以添加到booksb

检查以下代码:

books = [(17,5), (3,55), (5,12), (14,9), (16,1), (9,5), (5,6), (18,13), (19,7), (1,20), (4,12), (11,1), (8,6), (8,18), (3,4), (13,7), (17,22), (20,7)]
lista = [[(0,9), (3,10), (6,15)]]

booksa = []
booksb = []
for x in lista:
   for y in x:
       booksa.append(books[y[0]][0])
       booksb.append(books[y[1]][1])

print ("booksa = %s" %(booksa))
print ("booksb = %s" %(booksb))

输出:

booksa = [17, 14, 5]
booksb = [20, 12, 7]

答案 1 :(得分:1)

使用列表理解

books = [(17,5), (3,55), (5,12), (14,9), (16,1), (9,5), (5,6), (18,13), (19,7), (1,20), (4,12), (11,1), (8,6), (8,18), (3,4), (13,7), (17,22), (20,7)]
lista = [[(0,9), (3,10), (6,15)]]

booksa = [books[k[0]][0] for j in lista for k in j]
booksb = [books[k[1]][1] for j in lista for k in j]

"""
# output 
booksa = [17, 14, 5]
booksb = [20, 12, 7]
"""

答案 2 :(得分:0)

您可以使用元组拆包来提高可读性:

booksa = [books[i][0] for i, _ in lista[0]]
# [17, 14, 5]

booksb = [books[j][1] for _, j in lista[0]]
# [20, 12, 7]

如果lista中有多个子列表,请使用itertools.chain(lista)而不是lista[0]