我的库存程序输入如下
"Sqin.txt"数据读入,是一个cvs文件
AAC,D,20111207,9.83,9.83,9.83,9.83,100
AACC,D,20111207,3.46,3.47,3.4,3.4,13400
AACOW,D,20111207,0.3,0.3,0.3,0.3,500
AAME,D,20111207,1.99,1.99,1.95,1.99,8600
AAON,D,20111207,21.62,21.9,21.32,21.49,93200
AAPL,D,20111207,389.93,390.94,386.76,389.09,10892800
AATI,D,20111207,5.75,5.75,5.73,5.75,797900
输出为
dat1[]
['AAC', ['9.83', '9.83', '9.83', '9.83', '100'], ['9.83', '9.83', '9.83', '9.83', '100']]
dat1[0]是用于查找和数据更新的股票符号"ACC"Dat1[1….?]是EOD(一天结束)数据股票市场收盘时,EOD数据将在每个更新周期的dat1.insert(1,M)插入。伙计们,你们可以用一行代码把它写出来。到目前为止,我的代码已经超过30行了,所以查看我的代码并不重要。上面是一些简单输入和所需输出的示例。
如果你决定接受一些真实世界的编程,请保持冗长。声明您的变量,然后填充它,最后使用它们(例如)
M = []
M = q [0][3:] ## had to do it this way because 'ACC' made the variable M [] begin as a string (inmutable). So I could not add M to the data.-dat1[]- because -dat1[]- also became a string (inmutable strings how stupid). Had to force 'ACC' to be a list so I can create a list of lists -dat1-
Dat1.insert(1.M) ## -M- is used to add another list to the master.dat record
也许可以做一些蟒蛇式的,少一点冗长。
您应该使用以名称为关键字的字典:
import csv
import collections
filename = 'csv.txt'
with open(filename) as file_:
reader = csv.reader(file_)
data = collections.defaultdict(list)
for line in reader:
# line[1] contains "D" and line[2] is the date
key, value = line[0], line[3:]
data[key].append(value)
要添加数据,请执行data[name].insert(0, new_data)
。其中名称可以是AAC
,值是一个数据列表。这将把新数据放在列表的开头,就像你在帖子中所说的那样。
我推荐append
而不是insert
,它更快。如果您确实希望将数据添加到列表的开头,请使用collections.deque
而不是list
。