【发布时间】:2012-11-13 05:18:07
【问题描述】:
如何从迭代器的不同索引位置获取多个任意值?
How to get the n next values of a generator in a list (python) 和Get the nth item of a generator in Python 描述了使用itertools.islice 从迭代器中获取任意元素或连续子集。但是,如果我想要迭代器中不同位置的多个任意元素,而你不能只使用 islice 的 step 参数呢?
我正在尝试解决 Project Euler 的problem 40。我用
生成了一串连接整数iteration = (i for i in ''.join(map(str, (i for i in xrange(1,10**6)))))
现在我想获取索引为 1、10、100、1000、10000、100000、1000000 的元素,从 1 开始计数。我不能在这里使用 islice,因为每次调用 next 都会将当前值转换为向右让步。例如
next(islice(iteration, 1, 2)) + next(islice(iteration, 3, 4))
产生“26”而不是“24”。
更新(25.11.12,4:43 UTC+0):
感谢所有建议。我当前的代码如下所示:
it = (i for i in ''.join(map(str, (i for i in xrange(1,10**6)))))
ds = [int(nth(it, 10**i-10**(i-1)-1)) for i in range(7)]
return product(ds)
nth 的丑陋论点是生成一个由 0、8、89、899、8999 等组成的序列。
【问题讨论】:
-
当前代码的一个问题是它不会延迟生成数字(例如,将
10**6更改为10**7)——''.join将消耗它传递的内容。跨度>
标签: python iterator generator itertools