uol*_*lot 4 python for-loop python-itertools
我有一个项目列表(HTML表格行,用Beautiful Soup提取),我需要遍历列表并获得每个循环运行的偶数和奇数元素(我的意思是索引).我的代码看起来像这样:
for top, bottom in izip(table[::2], table[1::2]):
#do something with top
#do something else with bottom
Run Code Online (Sandbox Code Playgroud)
如何使这个代码不那么难看?或者也许是这样做的好方法?
编辑:
table[1::2], table[::2] => table[::2], table[1::2]
Run Code Online (Sandbox Code Playgroud)
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)]
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这样做的好处是可以正确处理不均匀的元素,这对您来说可能不重要.还有来自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)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2954 次 |
| 最近记录: |