简体   繁体   English

从Python列表中删除行-所有包含特定数字的行

[英]Removing Line From Python List - All Lines Containing Certain Number

I am looking to remove lines from a list that have a 0 in the 4th position. 我正在寻找从第4位为0的列表中删除行。 When I write out the file now it is not eliinating all the zero lines. 现在,当我写出文件时,它并没有消除所有零行。

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()

Use a list comprehension. 使用列表理解。

all_decisions = [x for x in all_decisions if x[4] != 0]

Or, use filter . 或者,使用filter

all_decisions = filter(lambda x: x[4] != 0, all_decisions)

The way you're doing this is not a good idea because you're modifying all_decisions while you're iterating over it. 执行此操作的方法不是一个好主意,因为在迭代时要修改all_decisions If you wanted to do it in a loop, I would suggest something like: 如果您想循环执行此操作,建议您执行以下操作:

temp = []
for x in all_decisions:
    if x[4] != 0:
        temp.append(x)
all_decisions = temp

But this is basically just a more verbose equivalent of the list comprehension and filter approaches I showed above. 但这基本上只是我上面显示的列表理解和filter方法的更详细的等效方法。

I think the problem is in your loop which eliminates the lines: 我认为问题出在您的循环中,从而消除了以下几行:

counter = 0
for j in all_decisions:
    if all_decisions[counter][4] == 0:
        all_decisions.remove(j)
    counter += 1

If you remove an element, you also bump the counter. 如果删除某个元素,则还会撞到计数器。 The consequence of that is that you're skipping lines. 其结果是您跳过了行。 So you might miss lines to be removed. 因此,您可能会错过要删除的行。 Try only bumping the counter if you didn't remove an element, ie 如果您没有删除元素,请尝试仅碰碰计数器,即

counter = 0
for j in all_decisions:
    if all_decisions[counter][4] == 0:
        all_decisions.remove(j)
    else:
        counter += 1

That being said, a more concise way to do what you want would be 话虽这么说,一种更简洁的方式来做你想要的

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)

The with clause will take care of calling close on ofile after executing the code, even if an exception is thrown. with子句将负责在执行代码后在ofile上调用close ,即使抛出异常也是如此。 Also, csv.writer features a writerows method which takes a list of rows. 另外, csv.writer具有一个writerows方法,该方法采用行列表。 Thirdly, you can use a generator expression d for d in all_decisions if d[4] != 0 to replace your filtering loop. 第三, d for d in all_decisions if d[4] != 0d for d in all_decisions if d[4] != 0可以d for d in all_decisions if d[4] != 0使用生成器表达式d for d in all_decisions if d[4] != 0来替换过滤循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM