【问题标题】:Remove 0 values in a list of list python删除列表 python 列表中的 0 个值
【发布时间】:2022-06-19 00:02:34
【问题描述】:

我需要删除 0 值,但我不知道怎么做,有人可以帮助我吗?

coord = [[(1.0, 1.0), (4.0, 2.0), 0, 0, 0, 0, (1.0, 5.0), 0, 0, (3.0, 3.0)], [(1.0, 1.0), (4.0, 2.0), 0, 0, 0, 0, (1.0, 5.0), 0, 0, (3.0, 3.0)]]

我需要那个坐标:

coord = [[(1.0, 1.0), (4.0, 2.0), (1.0, 5.0), (3.0, 3.0)], [(1.0, 1.0), (4.0, 2.0), (1.0, 5.0), (3.0, 3.0)]]

【问题讨论】:

    标签: python list


    【解决方案1】:

    您可以通过列表理解来做到这一点:

    [[i for i in j if i] for j in coord]
    

    输出:

    [[(1.0, 1.0), (4.0, 2.0), (1.0, 5.0), (3.0, 3.0)],
     [(1.0, 1.0), (4.0, 2.0), (1.0, 5.0), (3.0, 3.0)]]
    

    【讨论】:

      【解决方案2】:

      使用列表推导:

      [[item for item in sublist if item != 0] for sublist in coord]
      

      这个输出:

      [[(1.0, 1.0), (4.0, 2.0), (1.0, 5.0), (3.0, 3.0)], [(1.0, 1.0), (4.0, 2.0), (1.0, 5.0), (3.0, 3.0)]]
      

      【讨论】:

        猜你喜欢
        • 2013-04-12
        • 2023-03-26
        • 1970-01-01
        • 2020-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多