简体   繁体   English

Python从列表中删除项目

[英]Python remove items from list

I'm having some troubles with removing items from a list. 我在从列表中删除项目时遇到了一些麻烦。 I'm looking for a more elegant solution. 我正在寻找更优雅的解决方案。 Preferably a solution in one for-loop or filter. 优选地,在一个for环路​​或滤波器中的解决方案。

The objective of the piece of code: remove all empty entries and all entries starting with a '#' from the config handle. 这段代码的目的:从配置句柄中删除所有空条目和所有以“#”开头的条目。

At the moment i'm using: 目前,我正在使用:

# Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]

# Strip comment items from the configHandle
for item in configHandle:
    if item.startswith('#'):
        configHandle.remove(item)

# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle

This works but I think it is a bit of a nasty solution. 这可行,但是我认为这是一个令人讨厌的解决方案。

When I try: 当我尝试:

# Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]

# Strip comment items and empty items from the configHandle
for item in configHandle:
    if item.startswith('#'):
        configHandle.remove(item)
    elif len(item) == 0:
        configHandle.remove(item)

This, however, fails. 但是,这失败了。 I cannot figure out why. 我不知道为什么。

Can someone push me in the right direction? 有人可以将我推向正确的方向吗?

Because You're changing the list while iterating over it. 因为您在迭代列表时正在更改列表。 You can use a list comprehension to get ride of this problem: 您可以使用列表理解来解决此问题:

configHandle = [i for i in configHandle if i and not i.startswith('#')]

Also for opening a file you better to use a with statement that close the file at the end of the block automatically 1 : 同样,对于打开文件,您最好使用with语句,该语句会自动在块末尾1关闭文件:

with open('config.conf') as infile :
   configHandle = infile.splitlines()
   configHandle = [line for line in configHandle if line and not line.startswith('#')]

1. Because there is no guarantee for external links to be collected by garbage-collector. 1.因为不能保证垃圾收集器可以收集外部链接。 And you need to close them explicitly, which can be done by calling the close() method of a file object, or as mentioned as a more pythonic way use a with statement. 并且您需要显式关闭它们,这可以通过调用文件对象的close()方法来完成,或者如前所述,使用with语句以更Python的方式进行close()

迭代时不要删除项目,这是一个常见的陷阱

You aren't allowed to modify an item that you're iterating over. 不允许您修改要迭代的项目。

Instead you should use things like filter or list comprehensions. 相反,您应该使用诸如filter或list comprehensions之类的东西。

configHandle = filter(lambda a: (a != '') and not a.startswith('#'), configHandle)

Your filter expression is good; 您的filter表达式很好; just include the additional condition you're looking for: 仅包括您要查找的其他条件:

configHandle = filter(lambda a: a != '' and not a.startswith('#'), configHandle)


There are other options if you don't want to use filter , but, as has been stated in other answers, it is a very bad idea to attempt to modify a list while you are iterating through it. 如果您不想使用filter ,则还有其他选择,但是,正如其他答案中所述,在遍历列表时尝试修改列表是一个非常糟糕的主意。 The answers to this stackoverflow question provides alternatives to using filter to remove from a list based on a condition. 对这些问题的答案计算器问题提供替代使用filter ,以基于一个条件列表中删除。

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

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