python list comprehension and binary array

Generate a 4*4 matrix for i in [[x for x in range(1,5)] for x in range(1,5)]: print i [[x for x in range(1,5)] for x in range(1,5)] can be understood as [for x in range(1,5) [x for x in range(1,5)] ##=== [1,2,3,4] ### =========[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

[[y for y in range(1,5)] for x in range(1,5)] 可以理解为 [for x in range(1,5) [y for y in range(1,5)] ] # #========[and,and,and,and] ###========[[and,and,and,and],[and,and,and,and], [and,and,and,and],[and,and,and,and]] ###========[[1,1,1,1],[2,2,2,2 ],[3,3,3,3],[4,4,4,4]] 执行的过程为参考http://codingpy.com/article/python-list-comprehensions-explained-visually/

List comprehension implements two-dimensional array and its rotation by 90 degrees

a = [[x for x in range(1,10)] for x in range(1,10)]
def spin(list):
    n = len(a)
    for j in range(n-1):         ####执行对调 的 次数n-1
        for i in range(j,n):       ######  对调元素
            a[j][i],a[i][j] = a[i][j],a[j][i]
    for x in a:
        print x

The code idea of ​​​​rotation (90 degrees 4 4 array) square draws a diagonal line (the diagonal line of the upper left corner and the lower right corner), 90 degrees is to swap all elements with this diagonal as the symmetry axis. First The second swap is to swap the upper and left elements of the square. The second swap moves the upper and left lines in parallel (each element is on the top and left of the corresponding square) The third swap continues the second step, If you find that all elements are already on and to the left of the drawn square, then you end the swap line (3 steps for an array of 4 4, 4 steps for 5 5... You will find that n n requires n-1 steps ) When implementing the element object of the 4*4 array (write all the swaps by yourself), we will find that the key (a[key1][key2]) of the list corresponding to the elements during the swapping process will change according to the number of executions. The range of the swap cycle is range(j,n)j (range(n-1)) is the number of times the swap is executed (here, the swap of all the elements on the upper left is performed once), that is, the number of times the swap is executed The cycle is range( n-1)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325456609&siteId=291194637