代码之家  ›  专栏  ›  技术社区  ›  Bruce

忽略嵌套列表中的某些元素

  •  -2
  • Bruce  · 技术社区  · 7 年前

    我有以下清单

    [["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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Robᵩ    7 年前

    我会在你的任务中使用嵌套列表理解。

    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 已执行。

    这个 如果项目不在下拉列表中 可以由您可以编码的任何条件替换。例如:

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