列出Python中具有迭代之间可变状态的理解 [英] List comprehensions in Python with mutable state between iterations

查看:54
本文介绍了列出Python中具有迭代之间可变状态的理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了Python在列表之间具有可变状态外,我还有很多类似Python中的列表理解的功能.有什么办法可以通过列表理解吗?

I have something which is an awful lot like a list comprehension in Python, except that it shares mutable state between iterations. Is there any way to do it with a list comprehension?

def f(x):
    """ 5-bit LFSR """
    return (x >> 1) ^ (0x12*(x&1))

def batch(f, x, n):
    result = [x]
    for _ in xrange(1,n):
        x = f(x)
        result.append(x)
    return result

batch(f, 1, 5)

返回[1, 18, 9, 22, 11].这里重要的是batch函数,而不是f(x),这里只是一个简单的示例来说明问题.

which returns [1, 18, 9, 22, 11]. Here the important thing is the batch function, not f(x) which is here just a simple example to illustrate the issue.

或者我可以使用生成器来实现:

Alternatively I could implement using a generator:

def batch(f, x, n):
    yield x
    for _ in xrange(1,n):
        x = f(x)
        yield x

list(batch(f, 1, 5))

但是闻起来有点尴尬.我正在寻找的是这样的东西...

But it smells a little awkward. What I'm looking for is something like this...

batch = [??? for _ in xrange(n)]

推荐答案

否.故意没有.最终,他们放入了itertools.accumulate,这与以功能方式实现递归关系的官方推荐方法最接近,但在2.7中不存在.您可以从 docs 如果需要的话.

No. Deliberately no. Eventually they put in itertools.accumulate, which is the closest thing to an Officially Recommended way to implement recurrence relations in a functional manner, but it doesn't exist on 2.7. You could copy the "roughly equivalent to" Python implementation from the docs if you want.

这篇关于列出Python中具有迭代之间可变状态的理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆