Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中迭代函数以创建数组?_Python_Python 3.x_Scala - Fatal编程技术网

如何在Python中迭代函数以创建数组?

如何在Python中迭代函数以创建数组?,python,python-3.x,scala,Python,Python 3.x,Scala,在Scala中——因为它是一种函数式编程语言——我可以从起始值顺序迭代函数,以创建一个[f(initial)、f(f(initial))、f(f(initial))、…]数组。 例如,如果我想根据当前温度预测未来温度,我可以在Python中执行以下操作: import random as rnd def estimateTemp( previousTemp): # function to estimate the temperature, for simplicity assu

在Scala中——因为它是一种函数式编程语言——我可以从起始值顺序迭代函数,以创建一个[f(initial)、f(f(initial))、f(f(initial))、…]数组。 例如,如果我想根据当前温度预测未来温度,我可以在Python中执行以下操作:

import random as rnd    

def estimateTemp( previousTemp):
    # function to estimate the temperature, for simplicity assume it is as follows: 
    return( previousTemp * rnd.uniform(0.8, 1.2) + rnd.uniform(-1.0, 1.0))

Temperature = [0.0 for i in range(100)]

for i in range(1,100):
    Temperature[i] = estimateTemp( Temperature[i-1] )
前面代码的问题是,它使用for循环,需要预定义的温度数组,在许多语言中,可以用迭代器替换for循环。例如,在Scala中,通过使用迭代方法创建列表,您可以轻松完成上一个示例:

val Temperature = List.iterate(0.0,100)( n => 
      (n * (scala.util.Random.nextDouble()*0.4+0.8)) +
       (scala.util.Random.nextDouble()*2-1) 
)
这样的实现很容易理解,而且写得很清楚


Python已经实现了itertools模块来模拟一些函数式编程语言。itertools模块中有没有模仿Scala迭代法的方法?

不幸的是,
itertools
没有内置此功能。Haskell和Scala都有这个函数,这也让我感到困扰。我正在开发的
itertools
包装器有一些附加的帮助函数,包括前面提到的
iterate
函数

使用Alakasam的可运行示例:

import random as rnd
import alakazam as zz

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

Temperature = zz.iterate(estimateTemp, 0.0).take(100).list()
print(Temperature)

您可以将函数转换为一个无限生成器,并获取适当的切片:

import random as rnd    
from itertools import islice

def estimateTemp(startTemp):
    while 1:
        yield startTemp
        startTemp = (startTemp * rnd.uniform(0.8, 1.2) + rnd.uniform(-1.0, 1.0))

temperature = list(islice(estimateTemp(0.0), 0, 100))

使用itertools可以生成等效程序。累加
-:

from itertools import accumulate

accumulate(range(0, 100), lambda x, y => estimateTemp(x))

因此这里我们有一个累加器
x
,它被更新,而
y
参数(它是iterable的下一个元素)被忽略。我们使用它作为一种迭代100次的方式。

您的代码是否有效?@Arief是的,我想在Python中找到一种替代for循环的函数。由于Python实现了itertools来模仿一些函数式编程语言,我怀疑如果我使用其中一种itertools方法,我的代码可能会更清晰。我希望问题现在更清楚了。