gpt4 book ai didi

python - Python 列表理解中的附加条件

转载 作者:行者123 更新时间:2023-11-28 20:05:48 25 4
gpt4 key购买 nike

如何使用列表理解而不删除列表中间的空元素,从列表中删除所有开始的空项。这是一个例子:

desc = []
desc.append('')
desc.append('')
desc.append('')
desc.append('line 1')
desc.append('line 2')
desc.append('')
desc.append('')
desc.append('line 3')
filtered = [x for x in desc if x]
filtered
['line 1', 'line 2', 'line 3']

这是一个删除所有空项的简单列表理解:

filtered = [x for x in desc if x != '']

我试图使用列表理解来实现的是类似于此的东西:

for i in enumerate(desc):
if desc[0].strip() == '':
desc.pop(0)

最佳答案

使用itertools.dropwhile :

>>> from itertools import dropwhile

>>> lines = ['', '', 'line1', 'line2', '', '']
>>> list(dropwhile(lambda line: not line, lines))
['line1', 'line2', '', '']

除了 lambda,您可以使用 operator.not_ ,正如@JonClements 建议的那样:

>>> from operator import not_

>>> list(dropwhile(not_, lines))
['line1', 'line2', '', '']

关于python - Python 列表理解中的附加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27340209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com