我在清除列表中的项目时遇到了一些麻烦。我正在寻找更优雅的解决方案。优选地,在一个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)
然而,这将失败。我无法弄清楚为什么。
有人能把我推向正确的方向吗?
感谢您的回复!我完全不理解第一个解决方案(使用理解)。该行如何删除列表中的空条目?因为这也为我的技巧configHandle = [我为我在configHandle如果len(i)> 0,而不是我。startswith('#')] – DCB
@DCB当你编写'if line'时,python会检查'line'的有效性,如果它评估为True python则运行你的条件,在这种情况下,一个空字符串的计算结果为False。在这里阅读更多信息https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing – Kasramvd