python - 根据不同的索引位置删除列表列表中的公共(public)项

标签 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' 的索引位置创建列表似乎并不正确。

最佳答案

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

关于python - 根据不同的索引位置删除列表列表中的公共(public)项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318132/

相关文章:

python - cron 作业没有将输出写入正确的输出日志文件

Python/Scipy - 与 Quad Along Axis 集成

python - 如何使用 if-else 条件在数据集中插入缺失的行序列?

python - 对两个列表使用 max 函数有什么意义?

python - NameError:名称 'x' 未定义 Python

python - 引发 NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch : Reverse for 'login

python - 从 C++ 代码转换时 python 代码出现故障?

python-3.x - Python 3 - 面向对象编程 - 类和函数

python - Ansible Community.aws.aws_ssm 模块。错误!一名 worker 被发现已死亡

F# 中的列表理解与高阶函数