Detailed explanation of how to represent matrices in Python

黄舟
Release: 2017-05-28 11:08:31
Original
5794 people have browsed it

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
Copy after login

Result:

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

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
Copy after login

Result:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Copy after login

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
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!