忽略嵌套列表中的某些元素
ignoring certain elements in a nested list
我有以下列表
[["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
我会为你的任务使用嵌套列表理解。
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']]
我有以下列表
[["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
我会为你的任务使用嵌套列表理解。
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']]