我一直在玩一个试图更好地学习如何用Python编码的数据集。
我创建的代码完美无缺,但仅适用于CSV文件的一行(我有571行数据)。这将获取行,然后将第一个数字与第二个数字进行比较,具体取决于第一个数字是大于还是小,它会将该数字放入相应的列表中。然后代码移动到下一个值并执行相同的操作。
bigger = []
smaller = []
mL_ind = 1
add = 0
add_s = 0
gross = []
largest_val = []
net_total = []
initial = open('output.csv')
reader = csv.reader(initial)
mathLine = [line.split(',')[1] for line in initial]
del mathLine[0]
mathLine = list(map(float, mathLine))
for value in mathLine:
if value > mathLine[mL_ind]:
bigger.append(value)
mL_ind = mL_ind + 1
elif value < mathLine[mL_ind]:
smaller.append(value)
mL_ind = mL_ind + 1
for value in bigger:
add = value + add
for value in smaller:
add_s = value + add_s
total = add - add_s
gross.append(total)
largest = max(mathLine)
largest_val.append(largest)
net = total / largest
net_total.append(net)
我试图做的是使用索引(在line.split之后):mathLine = [line.split(&#39;,&#39;)[1] for line in initial] 作为迭代来移动CSV文件,以及作为我的while循环的计数器。但是,当我设置此项时,我会收到此行的错误:if value&gt; mathLine [mL_ind]
非常感谢任何帮助
答案 0 :(得分:0)
这对我有用......
导入csv
bigger = []
smaller = []
mL_ind = 1
add = 0
add_s = 0
gross = []
largest_val = []
net_total = []
initial = open('dummy.csv')
reader = csv.reader(initial)
mathLine = [line.split(',')[1] for line in initial]
print (mathLine)
del mathLine[0]
mathLine = list(map(float, mathLine))
for value in mathLine[:-1]:
if value > mathLine[mL_ind]:
bigger.append(value)
mL_ind += 1
elif value < mathLine[mL_ind]:
smaller.append(value)
mL_ind += 1
for value in bigger:
add = value + add
for value in smaller:
add_s = value + add_s
total = add - add_s
gross.append(total)
largest = max(mathLine)
largest_val.append(largest)
net = total / largest
net_total.append(net)
print (net_total)