我有一个名为 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 中执行 for x 时,它会毫无问题地遍历列表直到到达末尾?为什么要走出索引?
Python 3,谢谢。
请您参考如下方法:
它显然在前 7 次迭代中完成了您想要的操作。但在完成第 7 次迭代后,for 循环仍将仅遍历列表中更多元素中的 7 个,因此它将尝试访问 stock_data[10+6*7]。你的意思可能是:
closing_prices = stock_data[10::6]
stock_data[a:b:c] 返回 stock_data 的子列表,从索引 a 开始,取每个 cth 元素,直到但不包括索引 b。如果未指定,它们默认为 a=0、c=1、b=(length of the list)。这称为切片。
