简体   繁体   English

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

[英]Iterate over three lists with different lengths simultaneously

So I tried to iterate over 3 lists simultaneously using zip and itertools cycle in python 3, but it gave me something I didn't want. 因此,我尝试在python 3中使用zip和itertools循环同时迭代3个以上的列表,但它给了我一些我不想要的东西。 Suppose that I have 假设我有

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]

I have tried this: 我已经试过了:

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)

my output is: 我的输出是:

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
. .  .
. .  .
. .  .
. .  .
. .  .

and so on... 等等...

I expect the output: 我期望输出:

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
1 0 12
1 1 13
1 2 14
1 3 15
1 4 16
1 5 17
1 6 18
1 7 19
1 8 20
1 9 21
1 10 22
1 11 23
2 0 24
2 1 25
2 2 26
2 3 27
2 4 28
2 5 29
2 6 30
2 7 31
2 8 32
2 9 33
2 10 34
2 11 35
. .  .
. .  .
. .  .
. .  .
. .  .
11 9  141 
11 10 142
11 11 143

I have tried without using itertools cycle, using itertools.izip_longest and changing the order of iteration of lists. 我尝试过不使用itertools循环,使用itertools.izip_longest和更改列表迭代的顺序。 What should I do? 我该怎么办?

It appears you don't want to cycle through any lists at all. 您似乎根本不想循环浏览任何列表。 Instead you want to go through every element in b for each element in a , while incrementing c . 相反,你想通过每一个元素在b中的每个元素a ,同时增加c

Turn c into an iterator like so to increment it, and proceed with the nested for loop like so: 像这样将c变成一个迭代器以增加它,然后像下面这样继续嵌套的for循环:

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)

Output: 输出:

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
1 0 12
1 1 13
1 2 14
1 3 15
1 4 16
1 5 17
1 6 18
1 7 19
1 8 20
1 9 21
1 10 22
1 11 23
2 0 24
2 1 25
2 2 26
2 3 27
2 4 28
2 5 29
2 6 30
2 7 31
2 8 32
2 9 33
2 10 34
2 11 35
. .  .
. .  .
. .  .
. .  .
. .  .
11 9  141 
11 10 142
11 11 143

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM