在Python中从列表中获取n个项目组的惯用方法?
给定一个列表,
A = [1 2 3 4 5 6]
是否有任何惯用的(Pythonic)方式来迭代它,就好像它不是
B = [(1, 2) (3, 4) (5, 6)]
索引一样?这感觉像是 C 语言的遗留物:
for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]:
我情不自禁地觉得应该有一些巧妙的技巧,使用 itertools 或切片或其他东西。
(当然,一次两个只是一个例子;我想要一个适用于任何 n 的解决方案。)
编辑:相关 在 Python 中一次迭代 2(或 n)个字符的字符串 但即使是最干净的解决方案(接受,如果没有列表理解和 * 符号,使用 zip) 不能很好地推广到更高的 n 。
Given a list
A = [1 2 3 4 5 6]
Is there any idiomatic (Pythonic) way to iterate over it as though it were
B = [(1, 2) (3, 4) (5, 6)]
other than indexing? That feels like a holdover from C:
for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]:
I can't help but feel there should be some clever hack using itertools or slicing or something.
(Of course, two at a time is just an example; I'd like a solution that works for any n.)
Edit: related Iterate over a string 2 (or n) characters at a time in Python but even the cleanest solution (accepted, using zip) doesn't generalize well to higher n without a list comprehension and *-notation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 http://docs.python.org/library/itertools.html:
From http://docs.python.org/library/itertools.html: