简体   繁体   English

使用 enumerate() 和 takewhile() 在 python 中返回一个列表

[英]Using enumerate() and takewhile() to return a list in python

I'm trying to define a method to return a list of the first n elements of a Fibonacci generator using enumerate() and takewhile().我正在尝试定义一个方法来使用 enumerate() 和 takewhile() 返回斐波那契生成器的前 n 个元素的列表。 My code goes into an infinite loop and never checks the condition in takewhile() to stop iterating.我的代码进入无限循环,并且从不检查 takewhile() 中的条件以停止迭代。 I know islice() is much easier, but I need to define the method using only enumerate and takewhile.我知道 islice() 更容易,但我只需要使用 enumerate 和 takewhile 来定义方法。

from itertools import takewhile


def fibonacci_unbounded():
    (a, b) = (0, 1)
    while True:
        yield a
        (a, b) = (b, a + b)


def take_e(n, gen):
    fib_list = []
    for (i, elem) in enumerate(gen):
        if takewhile(i < n, gen):
            fib_list.append(elem)
        else:
            return fib_list


fibonacci = fibonacci_unbounded
n = 8

print(take_e(n, fibonacci()))

zip works much like enumerate when you use a range iterator.当您使用range迭代器时, zip工作方式与enumerate非常相似。 The nice part is that zip stops on the shortest iteration.好的部分是zip在最短的迭代中停止。 So ditch takewhile and use an enumerator that stops at the right place.因此, takewhile并使用停在正确位置的枚举器。

def fibonacci_unbounded():
    (a, b) = (0, 1)
    while True:
        yield a
        (a, b) = (b, a + b)

def take_e(n, gen):
    return list((elem) for _,elem in zip(range(n), gen))

fibonacci = fibonacci_unbounded
n = 8
print(take_e(n, fibonacci()))

If using takewhile and enumerate is a requirement, you should take values from the enumeration until the condition is met.如果需要使用takewhileenumerate ,则应从枚举中获取值,直到满足条件。

from itertools import takewhile

def fibonacci_unbounded():
    (a, b) = (0, 1)
    while True:
        yield a
        (a, b) = (b, a + b)

def take_e(n, gen):
    return list(val for _,val in takewhile(
        lambda i_val: i_val[0] < n, enumerate(gen)))

fibonacci = fibonacci_unbounded
n = 8
print(take_e(n, fibonacci()))

Here's a way that works.这是一种有效的方法。 I was hoping to find a way to not need to add the index into the logic so that you can test for the "nth" item returned:我希望找到一种不需要将索引添加到逻辑中的方法,以便您可以测试返回的“第 n 个”项目:

def fibonacci_unbounded():
    (a, b) = (0, 1)
    while True:
        yield a
        (a, b) = (b, a + b)

def take_e(n, gen):
    return [x[1] for x in takewhile(lambda x: x[0] < n, enumerate(gen()))]

print(take_e(9, fibonacci_unbounded))

Result:结果:

[0, 1, 1, 2, 3, 5, 8, 13, 21]

It would be simpler if I didn't have to use the takewhile .如果我不必使用takewhile会更简单。 I've never used it before, so I'm not aware if there are special tricks to using it.我以前从未使用过它,所以我不知道是否有使用它的特殊技巧。 It would be easier to just pass the count you desire into the base fibonacci generator and have it stop at the appropriate moment.将您想要的计数传递到基本斐波那契生成器并让它在适当的时刻停止会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM