Home  >  Article  >  Backend Development  >  Detailed explanation of how to represent matrices in Python

Detailed explanation of how to represent matrices in Python

黄舟
黄舟Original
2017-05-28 11:08:315795browse

This article mainly introduces the method of expressing matrices in Python, and analyzes the methods of expressing matrices in Python and related operations based on specific examples. Notes, friends in need can refer to the following

The examples in this article describe the method of representing matrices in Python. Share it with everyone for your reference, the details are as follows:

In c language, it represents an "integer 3 rows and 4 columns" matrix, which can be declared like this: int a[3][ 4]; In python, variables int cannot be declared, and dimensions cannot be listed. It can be expressed in the form of a list within a list. For example:

represents matrix , it can be like this:

count = 1
a = []
for i in range(0, 3):
  tmp = []
  for j in range(0, 3):
    tmp.append(count)
    count += 1
  a.append(tmp)
print a

Result:

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

But pay attention to one thing: initialization (when all assignments are 0), the following is wrong ! !

tmp = []
for j in range(0, 3):
  tmp.append(0)
a = []
for i in range(0, 3):
  a.append(tmp)
print a

Result:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Cause: The tmp of such a list is the same. If you change any row, other rows will be changed accordingly. Be careful! ! , the following is correct:

a = []
for i in range(0, 3):
  tmp = []
  for j in range(0, 3):
    tmp.append(0)
  a.append(tmp)
print a


The above is the detailed content of Detailed explanation of how to represent matrices in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn