0

i have list below

l = ["a1", "MYSQL1","emp", "b1", "MYSQL2","dep"]
for a, b,c in zip(l[::2], l[1::2], l[2::3]):
    print(a, b, c)

I got the first line properly but rest is coming wrong

My expected out

a1 MYSQL1 emp
b1 MYSQL2 dep
  • 1
    All the `::2` should be `::3` – Barmar May 11 '20 at 12:00
  • ``::2`` and ``1::2`` has a stride of 2, but ``2::3`` has a stride of 3. Do you intend a stride of 3 for all? – MisterMiyagi May 11 '20 at 12:00
  • Does this answer your question? [What is the most "pythonic" way to iterate over a list in chunks?](https://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks) ; or https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks – Tomerikoo May 11 '20 at 12:02
  • a = [1,2,3,4,5,6] b = zip(a[::3],a[1::3],a[2::3]) I don't understand why, but when i tried it on my python 2.7 command line, it works. – Zhd Zilin May 11 '20 at 12:06

2 Answers2

1

Change ::2 to ::3:

l = ["a1", "MYSQL","emp", "b1", "MYSQL","dep"]
for a, b,c in zip(l[::3], l[1::3], l[2::3]):
    print(a, b, c)

Output:

a1 MYSQL emp
b1 MYSQL dep
0

This works:

>>> N = 3
>>> a = ["a1", "MYSQL1","emp", "b1", "MYSQL2","dep"]
>>> for vals in zip(*[iter(a)]*N) :
...     print vals
... 
('a1', 'MYSQL1', 'emp')
('b1', 'MYSQL2', 'dep')
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43