我有一个名为 stock_data 的列表,其中包含以下数据:
['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close\n2013-06-28', '874.90', '881.84', '874.19', '880.37', '2349300', '880.37\n2013-06-27', '878.80', '884.69', '876.65', '877.07', '1926500', '877.07\n2013-06-26', '873.75', '878.00', '870.57', '873.65', '1831400', '873.65\n2013-06-25', '877.26', '879.68', '864.51', '866.20', '2553200', '866.20\n2013-06-24', '871.88', '876.32', '863.25', '869.79', '3016900', '869.79\n2013-06-21', '888.34', '889.88', '873.07', '880.93', '3982300', '880.93\n2013-06-20', '893.99', '901.00', '883.31', '884.74', '3372000', '884.74\n']
我想创建一个名为 closing_prices 的新列表,其中只有上面列表中的收盘价,我发现它是从上面列表中的元素 10 开始的每 6 个元素。
到目前为止,这是我的代码:
stock_data = []
for line in data:
stock_data.append(line)
closing_prices= []
count = 10
for item in stock_data:
closing_prices.append(stock_data[count])
print (closing_prices)
count = count + 6
这给出了这个结果:
['880.37']
['880.37', '877.07']
['880.37', '877.07', '873.65']
['880.37', '877.07', '873.65', '866.20']
['880.37', '877.07', '873.65', '866.20', '869.79']
['880.37', '877.07', '873.65', '866.20', '869.79', '880.93']
['880.37', '877.07', '873.65', '866.20', '869.79', '880.93', '884.74']
Traceback (most recent call last):
File "C:\Users\Usman\Documents\Developer\Python\Pearson Correlation\pearson_ce.py", line 34, in <module>
closing_prices.append(stock_data[count])
IndexError: list index out of range
显然我想要的是最后一行:
['880.37', '877.07', '873.65', '866.20', '869.79', '880.93', '884.74']
但是我一直在为列表索引超出范围而摸不着头脑,因为我认为当您在 stock_data 中为 x 执行操作时,它只会遍历列表直到它到达末尾而没有任何问题?为什么会出指数?
Python 3,谢谢。