我希望从列表中删除第4个位置为0的行。当我现在写出文件时,它并没有消除所有零线。
counter = 0
for j in all_decisions:
if all_decisions[counter][4] == 0:
all_decisions.remove(j)
counter += 1
ofile = open("non_zero_decisions1.csv","a")
writer = csv.writer(ofile, delimiter=',')
for each in all_decisions:
writer.writerow(each)
ofile.close()
答案 0 :(得分:5)
使用列表理解。
all_decisions = [x for x in all_decisions if x[4] != 0]
或者,使用filter
。
all_decisions = filter(lambda x: x[4] != 0, all_decisions)
你这样做的方式不是一个好主意,因为你在迭代时修改all_decisions
。如果你想在一个循环中做,我会建议像:
temp = []
for x in all_decisions:
if x[4] != 0:
temp.append(x)
all_decisions = temp
但这基本上只是我在上面展示的列表理解和filter
方法的更详细的等价物。
答案 1 :(得分:2)
我认为问题出在你的循环中,消除了这些行:
counter = 0
for j in all_decisions:
if all_decisions[counter][4] == 0:
all_decisions.remove(j)
counter += 1
如果删除元素,也会碰撞计数器。这样做的结果是你正在跳过线路。所以你可能会错过要删除的行。如果您没有删除元素,请尝试碰撞计数器,即
counter = 0
for j in all_decisions:
if all_decisions[counter][4] == 0:
all_decisions.remove(j)
else:
counter += 1
话虽如此,更简洁的方式来做你想做的事情
with open("non_zero_decisions1.csv","a") as ofile:
writer = csv.writer(ofile, delimiter=',')
writer.writerows(d for d in all_decisions if d[4] != 0)
with
子句将在执行代码后在close
上调用ofile
,即使抛出异常也是如此。此外,csv.writer
使用writerows
方法,该方法采用行列表。第三,您可以使用生成器表达式d for d in all_decisions if d[4] != 0
来替换过滤循环。