Py学习  »  Python

移除嵌套列表python中特定项之后的所有项

Bangbangbang • 4 年前 • 857 次点击  

我有下面的嵌套列表,我想删除之后的所有项目 (包括 ).

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']]

提前谢谢你的帮助!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53127
 
857 次点击  
文章 [ 2 ]  |  最新文章 4 年前
alissongranemann
Reply   •   1 楼
alissongranemann    4 年前

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)
Andrej Kesely
Reply   •   2 楼
Andrej Kesely    4 年前

你可以用 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]