Python implements matrix transpose analysis and python implements matrix
This article describes how to implement matrix transpose in Python. We will share this with you for your reference. The details are as follows:
A group member raised a question a few days ago: there is a list at hand, two elements in the list, such as [1, 2]. Then, they add new lists constantly, add to the original location. For example, add [3, 4] to extend the original list to [[1, 3], [2, 4], and then add [5, 6] to [1, 3, 5], [2, 4, 6], and so on.
In fact, it is easy to write a dual loop if you don't use your brains:
Def trans (m): a = [[] for I in m [0] for I in m: for j in range (len (I): a [j]. append (I [j]) return am = [[1, 2], [3, 4], [5, 6] # Imagine that the first list is original, the following is the print trans (m) # result: [[1, 3, 5], [2, 4, 6]
However, such code is ugly.
Take a closer look at the structure of m. Wait. This is not a dictionary.iteritems()
? Ifdict(m)
Then the result -- isn't it keys () and values?
So use the dictionary to convert it:
def trans(m): d = dict(m) return [d.keys(), d.values()]
But think about the bug. If the first element to be added to the list is the same, that is, the key of the converted dict is the same, it will definitely not work! Besides, if the original list is not two, but multiple, the dictionary cannot be used! Let alone this method. Let's take a good look at the shape of the list.
Then it was an accidental discovery:
What is the real-time sense of this transpose matrix?
Yes, the essence of this problem is to solve the transpose matrix. So it's easy, but you still have to worry about it:
def trans(m): for i in range(len(m)): for j in range(i): m[i][j], m[j][i] = m[j][i], m[i][j] return mm = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print trans(m)
In fact, it is still a little bug, it seems to be easy to use, but this matrix requires the same row and column length.
Finally, a great god in the group said: if it is just a transpose matrix, it would be better to directly zip it. This reminds us that the essence of zip is like this. Taking out the elements in the corresponding position in the list to form a new list is exactly what this question is about.
In the end, the python solution for this question (transpose matrix) is quite amazing:
def trans(m): return zip(*d)
That's all. The charm of python.