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

Python:如何使列表中的列表值为零

  •  0
  • Vondoe79  · 技术社区  · 7 年前

    child_Before = [[9, 12, 7, 3, 13, 14, 10, 5, 4, 11, 8, 6, 2],
                [1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1],
                [[1, 0], [1, 1]]]
    
        for elem in range(len(child_Before[0])):
            child_Before[0][elem] = 0
    

    预期结果如下:

     child_After = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1],
                    [[1, 0], [1, 1]]]
    

    然而,我认为应该有一种更简单的方法来完成这个练习。因此,我欢迎你的帮助。先谢谢你。

    3 回复  |  直到 7 年前
        1
  •  0
  •   Jonas Wolff    7 年前

    只是为了增加一个创造性的答案

    import numpy as np
    child_Before[0] = (np.array(child_Before[0])&0).tolist()
    

    这是一个糟糕的做法,因为我在senario中使用的是位运算,这是不直观的,而且我认为有一点可能我在bright站点上创建了2个循环xD,而创建所有零的时间复杂度是O(1)

        2
  •  0
  •   Walter    7 年前

    # Answer to this question - make first list in the list to be all 0
    child_Before[0] = [0] * len(child_Before[0])
    

    # Make all elements 0
    for child in range(len(child_Before)):
        child_Before[child] = [0] * len(child_Before[child])
    
        3
  •  0
  •   Osman Mamun    7 年前

    child_after = [[i if n != 0 else 0 for i in j] for n, j in enumerate(child_Before)]
    
    推荐文章