簡體   English   中英

從Python中的生成器獲取多個單個值

[英]Get multiple individual values from generator in Python

如何從迭代器的不同索引位置獲取多個任意值?

如何在列表(python)中 獲取 生成器的n個下一個值以及如何 在Python獲取生成器的n個項,描述了itertools.islice用於從迭代器獲取任意元素或連續子集的用法。 但是,如果我想要迭代器中不同位置的多個任意元素,而不能僅僅使用islice的step參數呢?

我正在嘗試解決Euler項目的問題40 我生成了一個由串聯的整數組成的字符串

iteration = (i for i in ''.join(map(str, (i for i in xrange(1,10**6)))))

現在,我想從索引1開始獲得索引為islice在這里我不能使用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等的序列。

(請注意,有更快的方法可以解決Euler#40。)

我的工作方式會有所不同。 而不是使用nth

>>> from itertools import chain, count, islice
>>> 
>>> it = chain.from_iterable(str(i) for i in count(1))
>>> wanted = {10**i for i in range(7)}
>>> scan_region = islice(it, max(wanted)+1)
>>> digits = [int(x) for i, x in enumerate(scan_region, 1) if i in wanted]
>>> digits
[1, 1, 5, 3, 7, 2, 1]

這樣,我不必進行任何減法操作即可確保索引正確。

這是來自itertools文檔的“食譜”部分 它返回iterablen個元素,並隨其使用:

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

您可以通過依次調用它來獲得1st,10th,100th等元素(請注意,迭代器已消耗,並且索引為零):

first = nth(iteration, 0)
tenth = nth(iteration, 8)  # since we've already taken one
hundredth = nth(iteration, 89)  # since we've already taken ten
# etc

另外,您可以每次使用tee並使用nth和不同的迭代器。 這樣,您不必擔心單個迭代器被消耗的事實。 另一方面,如果迭代器很長,則可能開始吞下內存。

就像提到的那樣查看nth我將着眼於簡化生成器:

from itertools import count

def concat():
    for i in count(1):
        for j in str(i):
            yield int(j)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM