根据不同的索引位置删除列表列表中的共同项目

时间:2019-08-01 23:20:30

标签: python python-3.x list

如果我有一个列表列表,并且我想删除'd'之后的所有项目,并且我想根据两个列表中'd'的索引位置执行此操作,我将如何处理如果每个列表中'd'的索引位置不同,则执行此操作。

还有比索引更好的方法吗?

ab_list = ['a', 'b', 'c' ,'d','e', 'f'], ['a', 'd', 'e', 'f', 'g']
loc=[]
for i in ab_list:
    loc.append(i.index('d'))
print(loc)

# output is [3, 1]

for i in ab_list:
    for l in loc:
        ab_list_keep=(i[0:l])
        print(ab_list_keep)
## output is 
#['a', 'b', 'c']
#['a']
#['a', 'd', 'e']
#['a']

输出的前两行是我想要的,但是从'd'的索引位置中列出列表似乎并不正确。

1 个答案:

答案 0 :(得分:0)

Python的内置itertools.takewhile方法专为这种情况而设计:

import itertools
ab_list = ['a', 'b', 'c' ,'d','e', 'f'],['a', 'd', 'e', 'f', 'g']
print([list(itertools.takewhile(lambda i: i != "d", sublist)) for sublist in ab_list])

输出:

[['a', 'b', 'c'], ['a']]