How to create nested lists in python?

前端 未结 5 383
无人及你
无人及你 2021-01-13 01:14

I know you can create easily nested lists in python like this:

[[1,2],[3,4]]

But how to create a 3x3x3 matrix of zeroes?

[[         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 01:54

    Just nest the multiplication syntax:

    [[[0] * 3] * 3] * 3
    

    It's therefore simple to express this operation using folds

    def zeros(dimensions):
        return reduce(lambda x, d: [x] * d, [0] + dimensions)
    

    Or if you want to avoid reference replication, so altering one item won't affect any other you should instead use copies:

    import copy
    def zeros(dimensions):
        item = 0
        for dimension in dimensions:
            item = map(copy.copy, [item] * dimension)
       return item
    

提交回复
热议问题