2014-09-04 47 views
0

這裏是我的代碼:我創建一個列表,需要返回初始值

import random 

def stock_sim(price,time,mu,std): 
    y=range(time) 
    for i in y: 
     y[i]=price+random.lognormvariate(mu,std) 
    return y 

print(stock_sim(100,5,0,.2)) 

它返回:

[101.44054391531468, 100.73246087607879, 101.00880842134261, 101.14332126597128, 100.79412638906443] 

我需要它返回:

[100, 101.44054391531468, 100.73246087607879, 101.00880842134261, 101.14332126597128] 

第一個價值應該是第一天的初始價格,然後是以下4個價格變化。

回答

0

一種可能性是

def stock_sim(price,time,mu,std): 
    return [price]+[price + random.lognormvariate(mu,std) for i in range(time)] 

還有許多其他的方式,一種可能是將項目插入到左邊,或事先在其他解決方案中創建列表。

def stock_sim(price,time,mu,std): 
    temp = [price + random.lognormvariate(mu,std) for i in range(time)] 
    temp.insert(0,price) 
    return temp 

我不確定你的列表會增長多少,如果性能可能會成問題。在這種情況下,一個德克將是更好的解決方案

from collections import deque 
def stock_sim(price,time,mu,std): 
    temp = deque([price + random.lognormvariate(mu,std) for i in range(time)]) 
    temp.appendleft(price) 
    return temp 
2

只要保持一個單獨的列表,並先加價格:

def stock_sim(price,time,mu,std): 
    y = [] 
    y.append(price) 
    for i in range(time): 
     y.append(price+random.lognormvariate(mu,std)) 
    return y 
+0

與請求的答案相比,這返回一個太多的項目。也許'範圍(1,時間)'而不是? – 2014-09-04 20:13:47

+0

@sharth,不知道OP是否錯過了一個條目,看起來第二個列表中缺少最後一個值 – 2014-09-04 20:16:44

+0

範圍(1,時間)消除了額外的一天。謝謝。 – Drazen 2014-09-04 20:24:30

相關問題