Python列表删除追加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12920561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python list remove append
提问by Trying_hard
I have a file I am putting into a list and I am wanting to take some things out of it, and append to another list ( I have no problem with that), the problem I run into is removing the things out of the first list. below is what I have tried but it only removes every other from the original list.
我有一个文件要放入列表中,我想从中取出一些内容,然后附加到另一个列表中(我对此没有问题),我遇到的问题是从第一个列表中删除内容. 下面是我尝试过的,但它只会从原始列表中删除所有其他内容。
list:
bob g1 3110
bob g2 244
bob g3 -433
greg fun112 10595
greg fun113 -1203
greg fun114 -3049.999
greg fun115 3808
greg fun116 320
greg got112 -600
greg got113 5958
greg got114 1249
file1 = open('test','rb').read().splitlines()
file1=sorted(file1)
test_group = ['fun','got']
test= []
for product in file1:
spt = product.split(",")
for line in spt:
if line[:3] in test_group:
x = test.append(product)
y = file1.remove(product)
the test [ ] list is fine all of the items I want in there go with no problem, but when I review file1 it only takes out every other one of 'fun' and 'got' lines
测试 [] 列表很好,我想要的所有项目都没有问题,但是当我查看 file1 时,它只会去掉“有趣”和“得到”行中的每一个
why is this only taking out every other one, and how do I fix it?
为什么这只是取出所有其他的,我该如何解决?
采纳答案by mata
Don't try to modify a list you're iterating over! That's not going to work!
不要尝试修改您正在迭代的列表!那是行不通的!
If you make a copy of the list, then it should work:
如果您制作列表的副本,那么它应该可以工作:
for product in file1[:]:
spt = product.split(",")
for line in spt:
if line[:3] in test_group:
x = test.append(product)
y = file1.remove(product)
回答by Cole Busby
It might be because of the negative integers, it could be reading those as ones to skip over? have you tested that?
可能是因为负整数,它可能将那些读作跳过?你测试过吗?
回答by Jon Clements
You don't want to be manipulating an object you're currently iterating over (if you try this with a dictionary for instance, you'll actually get an exception).
您不想操作当前正在迭代的对象(例如,如果您使用字典尝试此操作,您实际上会得到一个异常)。
Also, since list.appendadn list.removeare in-place, it always returns None- so there's no point assigning the result to anything.
此外,由于list.appenddnlist.remove是就地的,它总是返回None- 所以没有必要将结果分配给任何东西。
I'd do it something like the following:
我会这样做:
with open('test') as fin:
test = []
other = []
rows = (line.split() for line in fin)
for name, group, value in rows:
if group[:3] in ('fun', 'got'):
add = test.append
else:
add = other.append
add([name, group, value])

