2016-08-04 157 views
0

我在清除列表中的项目时遇到了一些麻烦。我正在寻找更优雅的解决方案。优选地,在一个for-loop或filter中提供解决方案。Python从列表中删除项目

该段代码的目标:从配置句柄中删除所有空条目和以'#'开头的所有条目。

目前我正在使用:

# 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 

这工作,但我认为这是一个有点讨厌的解决方案。

当我尝试:

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

然而,这将失败。我无法弄清楚为什么。

有人能把我推向正确的方向吗?

回答

0

您不允许修改正在迭代的项目。您可以使用filter或列表解析。

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

因为您在迭代列表时正在更改列表。您可以使用列表解析得到这个问题的坐:

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

还为打开一个文件,你最好使用with声明,在该块结束时自动关闭文件:

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

1.因为存在用于通过垃圾收集器来收集外部链路没有保证。而且你需要明确地关闭它们,这可以通过调用文件对象的close()方法来完成,或者像使用with语句的更为pythonic的方式来提到的那样。

+0

感谢您的回复!我完全不理解第一个解决方案(使用理解)。该行如何删除列表中的空条目?因为这也为我的技巧configHandle = [我为我在configHandle如果len(i)> 0,而不是我。startswith('#')] – DCB

+0

@DCB当你编写'if line'时,python会检查'line'的有效性,如果它评估为True python则运行你的条件,在这种情况下,一个空字符串的计算结果为False。在这里阅读更多信息https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing – Kasramvd

1

,而你迭代,这是一个常见的问题

0

filter表现还是不错的,不要取出物品;只是包括你正在寻找的附加条件:

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


还有,如果你不希望使用filter其他的选择,但是,正如在其他的答案已经指出,这是一个尝试修改列表的同时重复遍历整个列表非常糟糕。 this stackoverflow问题的答案提供了使用filter从基于条件的列表中移除的替代方法。