忽略嵌套lis中的某些元素

2024-09-24 22:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下清单

[["abc","cdf","efgh","x","hijk","y","z"],["xyz","qwerty","uiop","x","asdf","y","z"]]

我想有以下输出

[["abc","cdf","efgh","hijk"],["xyz","qwerty","uiop","asdf"]]

如何在这里执行拆分操作? PS:原始数据相当大。 原始数据:http://pasted.co/20f85ce5


Tags: http原始数据psabccocdfqwertyxyz
1条回答
网友
1楼 · 发布于 2024-09-24 22:20:59

我会用嵌套列表理解你的任务

old = [["abc","cdf","efgh","x","hijk","y","z"],["xyz","qwerty","uiop","x","asdf","y","z"]]

droplist = ["x", "y", "z"]
new = [[item for item in sublist if item not in droplist] for sublist in old]
print(new)

注意new列表的创建。外部列表压缩考虑每个子列表。内部列表考虑单个字符串

当执行if item not in droplist时,会出现筛选器

if item not in droplist可以由您可以编写的任何条件替换。例如:

new = [[item for item in sublist if len(item) >= 3] for sublist in old]

甚至:

def do_I_like_it(s):
    # Arbitrary code to decide if `s` is worth keeping
    return True
new = [[item for item in sublist if do_I_like_it(item)] for sublist in old]

如果要按项目在子列表中的位置移除项目,请使用切片:

# Remove last 2 elements of each sublist
new = [sublist[:-2] for sublist in old]
assert new == [['abc', 'cdf', 'efgh', 'x', 'hijk'], ['xyz', 'qwerty', 'uiop', 'x', 'asdf']]

相关问题 更多 >