Iterate over even and odd list items at the same time

I have a list of elements (which are HTML table rows retrieved using Beautiful Soup), and I need to iterate over the list and get even and odd elements (I mean the index) for each loop. My code is as follows:

for top, bottom in izip(table[::2], table[1::2]):
    #do something with top
    #do something else with bottom

How to make this code less ugly? Or maybe this is a good way to do this?

EDIT:

table[1::2], table[::2]  => table[::2], table[1::2]
+3
source share
3 answers

Try:

def alternate(i):
    i = iter(i)
    while True:
        yield(i.next(), i.next())

>>> list(alternate(range(10)))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

This solution works in any sequence, and not just in lists, and does not copy the sequence (it will be much more efficient if you want only the first few elements of a long sequence).

+4

izip - , , :

>>> def chunker(seq, size):
...     return (tuple(seq[pos:pos+size]) for pos in xrange(0, len(seq), size))
...
>>> x = range(11)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> chunker(x, 2)
<generator object <genexpr> at 0x00B44328>
>>> list(chunker(x, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10,)]
>>> list(izip(x[1::2], x[::2]))
[(1, 0), (3, 2), (5, 4), (7, 6), (9, 8)]

, , , . itertools:

>>> def grouper(n, iterable, fillvalue=None):
...     "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
...     args = [iter(iterable)] * n
...     return izip_longest(fillvalue=fillvalue, *args)
...
>>>
>>> from itertools import izip_longest
>>> list(grouper(2, x))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, None)]
+5

Looks good. My only suggestion was to wrap it in a function or method. This way you can give it a name ( evenOddIter()), which makes it more readable.

0
source

Source: https://habr.com/ru/post/1710128/


All Articles