An example of a transformation of a two dimensional array in python
- 2020-04-02 14:15:15
- OfStack
This article illustrates the transformation method of two-dimensional array in python. Share with you for your reference. Specific methods are as follows:
First look at the following code:
arr = [ [1, 2, 3], [4, 5, 6], [7, 8,9], [10, 11, 12]]
print map(list, zip(*arr))
print '_-------------------------------------------------'
print [[r[col] for r in arr] for col in range(len(arr[0]))]
The operation results are as follows:
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
_-------------------------------------------------
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
Here's why:
1. The first method
: the map (list, zip (* arr))
Zip ([iterable,... )
This function returns a list of tuples, where thei-th tuple contains thei-th element from each of the argument sequences or iterables.
Zip ()
This function returns a list of tuples where the ith tuple contains the ith element of each argument's element from the queue passed in the argument
Here's another example:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
Zip (*arr) actually returns [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)], except that each of its elements is a tuple
The map (func, a list) :
The func method is called for each element in the list, returning the list
Parameter *arr is python's syntax for passing arbitrary location-based parameters
2. The second method:
[[r[col] for r in arr] for col in range(len(arr[0]))]
The inner derivation changes the elements selected (from the row), and the outer derivation affects the selectors (that is, the columns)
I hope this article has helped you with your Python programming.