0

我有以下嵌套列表,我想删除My Profile之后的所有项目(包括My Profile)。

my_lst = [['John C, CEO & Co-Funder, ABC company','Eric P, CFO, QWE company','My Profile','Herber W, CTO, PPP company'],
['Eli S, AVP, ACV Company', 'My Profile','Brian M, Analyst, LPL company'],
['Diana F, Managing Director, MS company','Alan X, Associate, JPM company','My Profile', 'Jame R, Manager, AL company']]

我尝试了编码[[i for i in nested if i != 'My Profile'] for nested in my_lst],但只能从每个列表中删除我的个人资料。

我的预期输出:

[['John C, CEO & Co-Funder, ABC company','Eric P, CFO, QWE company'],
['Eli S, AVP, ACV Company'],
['Diana F, Managing Director, MS company','Alan X, Associate, JPM company']]

在此先感谢您的帮助!

4

2 回答 2

3

您可以itertools.takewhile用于此任务:

from itertools import takewhile

my_lst = [['John C, CEO & Co-Funder, ABC company','Eric P, CFO, QWE company','My Profile','Herber W, CTO, PPP company'],
['Eli S, AVP, ACV Company', 'My Profile','Brian M, Analyst, LPL company'],
['Diana F, Managing Director, MS company','Alan X, Associate, JPM company','My Profile', 'Jame R, Manager, AL company']]

out = []
for i in my_lst:
    out.append([*takewhile(lambda k: k!='My Profile', i)])

from pprint import pprint
pprint(out)

印刷:

[['John C, CEO & Co-Funder, ABC company', 'Eric P, CFO, QWE company'],
 ['Eli S, AVP, ACV Company'],
 ['Diana F, Managing Director, MS company', 'Alan X, Associate, JPM company']]

编辑(列表理解版本):

out = [[*takewhile(lambda k: k!='My Profile', i)] for i in my_lst]
于 2020-01-17T22:03:06.873 回答
2

使用列表理解,您可以执行以下操作:

my_lst = [['John C, CEO & Co-Funder, ABC company','Eric P, CFO, QWE company','My Profile','Herber W, CTO, PPP company'],
['Eli S, AVP, ACV Company', 'My Profile','Brian M, Analyst, LPL company'],
['Diana F, Managing Director, MS company','Alan X, Associate, JPM company','My Profile', 'Jame R, Manager, AL company']]
results = [nested[:nested.index('My Profile')] if 'My Profile' in nested else nested for nested in my_lst]

没有列表理解:

my_lst = [['John C, CEO & Co-Funder, ABC company','Eric P, CFO, QWE company','My Profile','Herber W, CTO, PPP company'],
    ['Eli S, AVP, ACV Company', 'My Profile','Brian M, Analyst, LPL company'],
    ['Diana F, Managing Director, MS company','Alan X, Associate, JPM company','My Profile', 'Jame R, Manager, AL company']]
results = []
for nested in my_lst:
    filtered = nested[:nested.index('My Profile')] if 'My Profile' in nested else nested
    results.append(filtered)
于 2020-01-17T22:07:13.637 回答