How to get all array edges?

前端 未结 5 1321
攒了一身酷
攒了一身酷 2021-01-05 08:17

I have a n x n array, and want to receive its outline values. For example,

[4,5,6,7]

[2,2,6,3]

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 08:39

    Assuming your list is in the following format:

    l = [
         [4, 5, 6, 7],
         [2, 2, 6, 3],
         [4, 4, 9, 4],
         [8, 1, 6, 1]
        ]
    

    You can achieve what you want with this quick one-liner, using list comprehensions:

    out = list(l[0]) +  # [4, 5, 6, 7]
          list([i[-1] for i in l[1:-1]]) +  # [3, 4]
          list(reversed(l[-1])) +  # [1, 6, 1, 8]
          list(reversed([i[0] for i in l[1:-1]])) # [4, 2]
    
    print(out)  # gives [4, 5, 6, 7, 3, 4, 1, 6, 1, 8, 4, 2]
    

    This works whether you have a plain python list or a numpy array.

    Regarding efficiency, using %timeit on a 20000x20000 matrix, this method took 16.4ms.

    l = np.random.random(20000, 20000)
    %timeit list(l[0]) + list(...) + list(...) + list(...)
    100 loops, best of 3: 16.4 ms per loop
    

    I'm sure there are more efficient methods to accomplish this task, but I think that's pretty good for a one-liner solution.

提交回复
热议问题