猿问

Python - 循环遍历多个列表的所有实例

有没有更好的方法来循环 Python 中多个列表的每个组合?例如...


list1 = [1,2,3,4]

list2 = [6,7,8]


for i in list1:

   for j in list2:

      print(str(i) + ", " + str(j))


1, 6

1, 7

1, 8

2, 6

2, 7

2, 8

3, 6

3, 7

3, 8

4, 6

4, 7

4, 8

我问是因为我想在找到一个值后跳出两个循环。我不想使用 bool 标志来跳出顶级循环。到目前为止我看到的所有答案都说使用 zip,但这不是一回事。zip 将产生以下内容。


1, 6

2, 7

3, 8

如果你使用地图,你会得到以下,这也不是我要找的。


1, 6

2, 7

3, 8

4, None


潇湘沐
浏览 220回答 4
4回答

喵喔喔

你可以itertools.product像这样使用:list1 = [1,2,3,4]list2 = [6,7,8]find_this_value = (1, 8)found_value = Falsefor permutation in itertools.product(list1, list2):    if permutation == find_this_value:        found_value = True        breakif found_value:    pass  # Take actionitertools.product返回一个生成器,其中包含 2 个列表的所有可能排列。然后,您只需迭代这些,并搜索直到找到您想要的值。

慕沐林林

您是否尝试过使用列表理解[(x, y) for x in [1,2,3,4]  for y in [6,7,8]]

忽然笑

如果您不想itertools.product按照另一个答案中的建议使用,您可以将其包装在一个函数中并返回:list1 = [1,2,3,4]list2 = [6,7,8]def findNumbers(x, y):    for i in list1:       for j in list2:          print(str(i) + ", " + str(j))          if (x, y) == (i, j):              return (x, y)输出:>>> findNumbers(2, 7)1, 61, 71, 82, 62, 7(2, 7)
随时随地看视频慕课网APP

相关分类

Python
我要回答