同时遍历三个具有不同长度的列表

时间:2019-04-18 18:37:46

标签: python

因此,我尝试在python 3中使用zip和itertools循环同时遍历3个列表,但这给了我一些我不想要的东西。假设我有

import ipywidgets as widgets

widgets.Checkbox(
    value=False,
    description= ('account'),
    disabled=False
)

我已经尝试过了:

list_a = [0,1,2,3,4,5,6,7,8,9,10,11]

list_b = [0,1,2,3,4,5,6,7,8,9,10,11]

list_c = [0,1,2,3,4,5,6,7,8,9,10,11,
          12,13,14,15,16,17,18,19,20,21,22,23,
          24,25,26,27,28,29,30,31,32,33,34,35,
          36,37,38,39,40,41,42,43,44,45,46,47,
          48,49,50,51,52,53,54,55,56,57,58,59,
          60,61,62,63,64,65,66,67,68,69,70,71,
          72,73,74,75,76,77,78,79,80,81,82,83,
          84,85,86,87,88,89,90,91,92,93,94,95,
          96,97,98,99,100,101,102,103,104,105,106,107,
          108,109,110,111,112,113,114,115,116,117,118,119,
          120,121,122,123,124,125,126,127,128,129,130,131,
          132,133,134,135,136,137,138,139,140,141,142,143]

我的输出是:

from itertools import cycle
for val_a in list_a:
    for val_b, val_c in zip(cycle(list_b), list_c):
        print(val_a, val_b, val_c)

以此类推...

我希望输出:

0 0 0
0 1 1
0 2 2
0 3 3
0 4 4
0 5 5
0 6 6
0 7 7
0 8 8
0 9 9
0 10 10
0 11 11
0 0 12
0 1 13
0 2 14
0 3 15
0 4 16
0 5 17
0 6 18
0 7 19
0 8 20
0 9 21
0 10 22
0 11 23
0 0 24
0 1 25
0 2 26
0 3 27
0 4 28
0 5 29
0 6 30
0 7 31
0 8 32
0 9 33
0 10 34
0 11 35
. .  .
. .  .
. .  .
. .  .
. .  .

我尝试过不使用itertools循环,使用itertools.izip_longest并更改列表的迭代顺序。我该怎么办?

1 个答案:

答案 0 :(得分:3)

您似乎根本不想循环浏览任何列表。相反,您想对Item中的每个元素浏览b中的每个元素,同时递增a

c变成一个迭代器,使其递增,然后继续嵌套的for循环,如下所示:

c

输出:

iter_c = iter(list_c)
for val_a in list_a:
    for val_b, val_c in zip(list_b, iter_c):
        print(val_a, val_b, val_c)