【问题标题】:idiomatic way to take groups of n items from a list in Python? [duplicate]从 Python 中的列表中获取 n 个项目组的惯用方法? [复制]
【发布时间】:2011-01-28 12:32:56
【问题描述】:

给定一个列表

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 或切片或其他东西的巧妙 hack。

(当然,一次两个只是一个例子;我想要一个适用于任何 n 的解决方案。)

编辑:相关 Iterate over a string 2 (or n) characters at a time in Python 但即使是最干净的解决方案(已接受,使用 zip)也不能很好地推广到更高的 n 没有列表理解和 *-notation。

【问题讨论】:

标签: python iteration


【解决方案1】:

来自http://docs.python.org/library/itertools.html

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

i = grouper(3,range(100))
i.next()
(0, 1, 2)

【讨论】:

  • 这可能不是主观惯用的或避免列表理解和 * 符号,但它是“pythonic”足以在文档中。
  • 啊,我知道它存在于某个地方。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-09-13
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多