我正在使用for循环来更新Numpy数组,但它似乎并没有起作用。我做错了什么?
我的代码
public class TestModel {
private String testText;
public TestModel() {
}
public TestModel(String testText) {
this.testText = testText;
}
public String getTestText() {
return testText;
}
public void setTestText(String testText) {
this.testText = testText;
}
}
我按顺序输出3个打印命令
import pandas as pd
import pandas_datareader as pdr
import datetime as dt
from dateutil.relativedelta import relativedelta
import matplotlib.finance as mf
import numpy as np
import scipy as sp
def pull_price(ticker):
df = pd.read_csv(ticker+'.csv')
df1=np.array(df['Adj Close'])
return df1
tickers=['^DJI','^GSPC','^IXIC','^GDAXI','^HSI','^FCHI','^N225']
dic={}
for i in tickers:
dic[i]=pull_price(i)
for i in tickers:
count = len(dic[i])
for j in range(0,count):
try:
dic[i][j] = float(dic[i][j])
except ValueError:
dic[i][j] = float(dic[i][j-1])
dic_1= dic
print(dic['^GSPC'][0])
for i in tickers:
count = len(dic_1[i])
for j in range(0,count):
dic_1[i][j] = np.log(dic_1[i][j])
print(dic_1['^GSPC'][0])
print(dic['^GSPC'][0])
对于第一个411.410004
6.01959029389
6.01959029389
命令,它会显示正确的值。
但是对于接下来的2 Print
命令,为什么它显示相同的值。我只是更新Print
而不是dic_1
。我做错了什么?
答案 0 :(得分:1)
当你这样做时:
dict1 = dict(a=1)
dict2 = dict1
dict1和dict2都指向同一个字典。名称不同,但两个名称都指的是相同的数据结构。这意味着:
dict2['a'] = 2
print(dict1)
{'a': 2}
如果你想让dict2成为dict1的副本,请明确地将其作为副本:
dict2 = dict1.copy()
啊,因为你字典的元素本身也是字典,你需要做一个深层复制:
import deepcopy
dict2 = deepcopy.copy(dict1)