生成一个序列,保留下一个元素python中的前一个元素

时间:2013-06-10 15:15:40

标签: python

我想在列表中生成一个序列,我知道如何使用for循环执行此操作,但是如果我想生成列表以便先前生成的元素包含在下一个元素中,我该怎么做这个?我很不确定

即生成列表,使其项目为:

其中x只是一个符号

[x,(x)*(x+1),(x)*(x+1)*(x+2)]

而不是[x,x+1,x+2]

任何帮助都非常感谢!

6 个答案:

答案 0 :(得分:6)

我喜欢使用发生器来做这类事情。

def sequence(x, N):
    i = 0
    result = 1
    while i < N:
        result *= (x + i)
        i += 1
        yield result

>>> list(sequence(5, 10))
[5, 30, 210, 1680, 15120, 151200, 1663200, 19958400, 259459200, 3632428800L]

如果你安装了numpy,这会更快:

np.multiply.accumulate(np.arange(x, x + N))

答案 1 :(得分:2)

基本上,您需要在元素之间保持状态,并且列表理解不会为您做到这一点。维持状态的几种方法是:a)使用生成器,b)使用类EDIT或c)闭包。

使用发电机

def product(x, n):
    accumulator = 1
    for i in xrange(n + 1):
        accumulator *= x + i
        yield accumulator

x = 5
print [n for n in product(x, 2)]
# or just list(product(x, 2))

或者,使用类来维护状态

class Accumulator(object):

    def __init__(self):
        self.value = 1
        self.count = 0

    def __call__(self, x):
        self.value *= x + self.count
        self.count += 1
        return self.value

a = Accumulator()
x = 5
print [a(x) for _ in xrange(3)]

...类方法的好处是你可以在每次迭代时对x使用不同的值,例如:

b = Accumulator()
print [b(x) for x in [1, 2, 3]]
>>> [1, 3, 15]

编辑:

为了彻底,关闭也会起作用:

def accumulator():

    # we need a container here because closures keep variables by reference; could have used a list too
    state = {'value': 1, 'count': 0}

    def accumulate(x):
        state['value'] *= x + state['count']
        state['count'] += 1
        return state['value']

    return accumulate

a = accumulator()
print [a(5) for _ in xrange(3)]

答案 2 :(得分:0)

试试这个。 Deque用于快速访问构造列表末尾的元素,以及持续的附加时间。 pol [-1]表示队列中的最后一个元素。

from collections import deque
def multCum(f, x, end):
    pol = deque([x])
    for i in range(1, end):
        pol.append(f(pol[-1],(x+i)))
    return list(pol)

def f(x, y):
    return x * y

multCum(f, 1, 3)

[1, 2, 6]

答案 3 :(得分:0)

使用带有列表推导的生成器。

def reqd(x, n):
    '''x is the number and n is number of elements '''
    yield x

    i = 0
    original = x
    while i < n:
        i += 1
        x *= (original + i)
        yield x

x = 2
listt = [a for a in reqd(x, 10)]
print listt

最后更改列表理解以获取所需的列表。

答案 4 :(得分:0)

使用for-comprehensions和自定义运算符进行更多惯用黑客攻击:

def n(a):
    global previous
    previous = a
    return a

[n(previous * (x+i)) for previous in [1] for i in range(0,3)]

收益率,如果x == 1,

[1, 2, 6]

答案 5 :(得分:0)

计算上浪费但完成工作

from operator import mul
z = range(5, 11)
print z                                                                     
[5, 6, 7, 8, 9, 10]

[reduce(mul, z[:i]) for i in range(1, len(z))]                              
[5, 30, 210, 1680, 15120]