You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中迭代函数生成数组?替代for循环的实现方案

Functional Approach to Generate Iterated Temperature Sequence in Python

Hey there! Since you're used to functional languages like Scala where you can easily generate sequences by iterating a function from an initial value, let's fix that Python code to ditch the for loop and pre-allocated array. Here are two clean, functional-style solutions:

Using itertools.accumulate (Standard Library)

Python's itertools.accumulate is perfect for this—it behaves just like Scala's iterate method. Starting from an initial value, it repeatedly applies your function to the previous result and yields each step.

For Python 3.8+, you can use the initial parameter to keep things concise:

import random as rnd
from itertools import accumulate, repeat

def estimateTemp(previousTemp):
    return previousTemp * rnd.uniform(0.8, 1.2) + rnd.uniform(-1.0, 1.0)

# Generate 100 elements: start at 0.0, apply estimateTemp 99 times
temperature = list(accumulate(repeat(None, 99), estimateTemp, initial=0.0))
  • repeat(None, 99) creates 99 dummy values (we don't use them—our function only cares about the previous temperature)
  • accumulate starts with 0.0, then runs estimateTemp on each previous result 99 times
  • Convert the iterator to a list to get your full sequence

If you need compatibility with older Python versions, use this alternative:

temperature = list(accumulate([0.0] + [None]*99, lambda prev, _: estimateTemp(prev)))

Custom Generator Function (Flexible & Readable)

If you want something more explicit and reusable, write a simple generator function that yields each step of the iteration:

import random as rnd

def estimateTemp(previousTemp):
    return previousTemp * rnd.uniform(0.8, 1.2) + rnd.uniform(-1.0, 1.0)

def iterate_func(initial_val, func, num_elements):
    current = initial_val
    yield current
    for _ in range(num_elements - 1):
        current = func(current)
        yield current

# Generate your 100-temperature sequence
temperature = list(iterate_func(0.0, estimateTemp, 100))

This generator is easy to modify—you could add a stop condition (e.g., stop if temperature goes outside a specific range) without changing the rest of your code.

Both approaches eliminate the need to pre-allocate an array and replace the imperative for loop with a functional, declarative style that aligns with what you'd do in Scala.

内容的提问来源于stack exchange,提问作者SheperoMah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:18:46