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']]
我会用嵌套列表理解你的任务
注意
new
列表的创建。外部列表压缩考虑每个子列表。内部列表考虑单个字符串当执行
if item not in droplist
时,会出现筛选器if item not in droplist
可以由您可以编写的任何条件替换。例如:甚至:
如果要按项目在子列表中的位置移除项目,请使用切片:
相关问题 更多 >
编程相关推荐