python:根据字符串名称过滤字符串列表

时间:2016-06-27 12:05:02

标签: python list

我有一个字符串列表,如下所示:

li1 = ['pin 2.3','vlo 5.4', 'lu 1.3', '3 packages installed', '', 'bla']

l12 = ['pin 2.3','vlo 5.4', '2 packages installed', 'bla', 'bla']

我想从列表中筛选出已安装的字符串'x packages'以及后面的字符串:

out1 = ['pin 2.3','vlo 5.4', 'lu 1.3']


out2 = ['pin 2.3','vlo 5.4']

如何使用列表理解来做到这一点?感谢

3 个答案:

答案 0 :(得分:6)

您可以使用itertools.takewhile,它会从列表中获取项目,直到未通过给定条件:

from itertools import takewhile

l12 = ['pin 2.3','vlo 5.4', '2 packages installed', 'bla', 'bla']
li1 = ['pin 2.3','vlo 5.4', 'lu 1.3', '3 packages installed', '', 'bla']



r12 = takewhile(lambda x: "packages installed" not in x, l12)
ri1 = takewhile(lambda x: "packages installed" not in x, li1)
print(list(r12))
# ['pin 2.3', 'vlo 5.4']

print(list(ri1))
# ['pin 2.3', 'vlo 5.4', 'lu 1.3']

答案 1 :(得分:1)

简单的事情:

li1 = ['pin 2.3','vlo 5.4', 'lu 1.3', '3 packages installed', '', 'bla']

out1 = []
for x in li1:
    if "packages installed" in x:
        break
    out1.append(x)

print(out1)
# ['pin 2.3', 'vlo 5.4', 'lu 1.3']
编辑:好像我有点迟了。

答案 2 :(得分:-1)

如果你想要一个新列表,

itertools.takewhile效果很好。要修改原始列表就地,您可以执行以下操作:

>>> L = ['pin 2.3','vlo 5.4', '2 packages installed', 'bla-bla']
>>> for i, v in enumerate(L):
...     if "packages installed" in v:
...         del L[i:]
...         break
... 
>>> L
['pin 2.3', 'vlo 5.4']