Как найти сумму элементов двумерного массива python

I want to sum a 2 dimensional array in python:

Here is what I have:

def sum1(input):
    sum = 0
    for row in range (len(input)-1):
        for col in range(len(input[0])-1):
            sum = sum + input[row][col]

    return sum


print sum1([[1, 2],[3, 4],[5, 6]])

It displays 4 instead of 21 (1+2+3+4+5+6 = 21). Where is my mistake?

Eric Leschinski's user avatar

asked May 23, 2012 at 3:43

Ronaldinho Learn Coding's user avatar

1

I think this is better:

 >>> x=[[1, 2],[3, 4],[5, 6]]                                                   
>>> sum(sum(x,[]))                                                             
21

answered Nov 27, 2012 at 6:07

hit9's user avatar

3

You could rewrite that function as,

def sum1(input):
    return sum(map(sum, input))

Basically, map(sum, input) will return a list with the sums across all your rows, then, the outer most sum will add up that list.

Example:

>>> a=[[1,2],[3,4]]
>>> sum(map(sum, a))
10

Eric Leschinski's user avatar

answered May 23, 2012 at 3:58

machow's user avatar

machowmachow

1,0341 gold badge9 silver badges16 bronze badges

1

This is yet another alternate Solution

In [1]: a=[[1, 2],[3, 4],[5, 6]]
In [2]: sum([sum(i) for i in a])
Out[2]: 21

answered May 14, 2015 at 16:44

Ajay's user avatar

AjayAjay

5,2072 gold badges23 silver badges30 bronze badges

0

And numpy solution is just:

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result:

>>> b=np.sum(x)
   print(b)
21

MAYUR K's user avatar

answered May 23, 2012 at 3:50

Akavall's user avatar

AkavallAkavall

81.8k51 gold badges205 silver badges249 bronze badges

3

Better still, forget the index counters and just iterate over the items themselves:

def sum1(input):
    my_sum = 0
    for row in input:
        my_sum += sum(row)
    return my_sum

print sum1([[1, 2],[3, 4],[5, 6]])

One of the nice (and idiomatic) features of Python is letting it do the counting for you. sum() is a built-in and you should not use names of built-ins for your own identifiers.

answered May 23, 2012 at 3:59

msw's user avatar

mswmsw

42.6k9 gold badges87 silver badges112 bronze badges

This is the issue

for row in range (len(input)-1):
    for col in range(len(input[0])-1):

try

for row in range (len(input)):
    for col in range(len(input[0])):

Python’s range(x) goes from 0..x-1 already

range(…)
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

answered May 23, 2012 at 3:45

dfb's user avatar

dfbdfb

13.1k2 gold badges30 silver badges52 bronze badges

range() in python excludes the last element. In other words, range(1, 5) is [1, 5) or [1, 4]. So you should just use len(input) to iterate over the rows/columns.

def sum1(input):
    sum = 0
    for row in range (len(input)):
        for col in range(len(input[0])):
            sum = sum + input[row][col]

    return sum

answered May 23, 2012 at 3:45

spinlok's user avatar

spinlokspinlok

3,54318 silver badges27 bronze badges

Don’t put -1 in range(len(input)-1) instead use:

range(len(input))

range automatically returns a list one less than the argument value so no need of explicitly giving -1

answered May 23, 2012 at 3:46

Kartik Anand's user avatar

Kartik AnandKartik Anand

4,4755 gold badges41 silver badges72 bronze badges

def sum1(input):
    return sum([sum(x) for x in input])

answered Sep 13, 2018 at 22:49

J F Fitch's user avatar

J F FitchJ F Fitch

1161 silver badge3 bronze badges

Quick answer, use…

total = sum(map(sum,[array]))

where [array] is your array title.

Nuwan Alawatta's user avatar

answered Apr 1, 2018 at 20:54

Finger Picking Good's user avatar

1

In Python 3.7

import numpy as np
x = np.array([ [1,2], [3,4] ])
sum(sum(x))

outputs

10

answered Jan 21, 2019 at 14:51

Rich006's user avatar

Speed comparison

import random
import timeit
import numpy
x = [[random.random() for i in range(100)] for j in range(100)]
xnp = np.array(x)

Methods

print("Sum python array:")
%timeit sum(map(sum,x))
%timeit sum([sum(i) for i in x])
%timeit sum(sum(x,[]))
%timeit sum([x[i][j] for i in range(100) for j in range(100)])

print("Convert to numpy, then sum:")
%timeit np.sum(np.array(x))
%timeit sum(sum(np.array(x)))

print("Sum numpy array:")
%timeit np.sum(xnp)
%timeit sum(sum(xnp))

Results

Sum python array:
130 µs ± 3.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
149 µs ± 4.16 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
3.05 ms ± 44.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Convert to numpy, then sum:
1.36 ms ± 90.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.63 ms ± 26.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Sum numpy array:
24.6 µs ± 1.95 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
301 µs ± 4.78 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

answered Apr 5, 2022 at 10:13

Erik's user avatar

ErikErik

316 bronze badges

1

It seems like a general consensus is that numpy is a complicated solution. In comparison to simpler algorithms. But for the sake of the answer being present:

import numpy as np


def addarrays(arr):

    b = np.sum(arr)
    return sum(b)


array_1 = [
  [1, 2],
  [3, 4],
  [5, 6]
]
print(addarrays(array_1))

This appears to be the preferred solution:

x=[[1, 2],[3, 4],[5, 6]]                                                   
sum(sum(x,[]))                                                             

answered Sep 26, 2019 at 0:14

peyo's user avatar

peyopeyo

3394 silver badges14 bronze badges

def sum1(input):
    sum = 0
    for row in input:
        for col in row:
            sum += col
    return sum
print(sum1([[1, 2],[3, 4],[5, 6]]))

Sefan's user avatar

Sefan

6991 gold badge8 silver badges23 bronze badges

answered Aug 17, 2021 at 7:57

Mbuthi Mungai's user avatar

def sum1(input):
    sum = 0
    for row in range (len(input)-1):
        for col in range(len(input[0])-1):
            sum = sum + input[row][col]

    return sum


print (sum1([[1, 2],[3, 4],[5, 6]]))

You had a problem with parenthesis at the print command….
This solution will be good now
The correct solution in Visual Studio Code

McLovin's user avatar

McLovin

5598 silver badges20 bronze badges

answered Aug 8, 2022 at 17:12

OTIENO BRIAN's user avatar

1

I think this is what you are trying to do

def sum1(arr):
sum = 0
for i in range(len(arr)):
    for j in range(len(arr[0])):
        sum += arr[i][j]
return sum

print(sum1([[1, 2], [3, 4], [5, 6]]))

answered Mar 15 at 14:57

Saad Muhammad's user avatar

1

For many languages such as Java and C++, arrays and lists are different objects. C++ doesn’t even technically have “lists” and Java has a hybrid object called an ArrayList. While there are arrays in Python, such as numpy arrays, Python’s most common sequence or series collection is a list object. 

Python list objects may contain entries of any type from numbers to strings to dictionaries, and may even contain multiple types. I’ll be using “array” and “list” interchangeably in this post because they are used in almost the exact same way in Python. In this post we’re going to cover how to sum a 2D list (or array) of numbers in Python. We’ll cover the following sections:

  • What is a 2D Array or List in Python
  • How Do You Sum an Array?
  • How Do You Sum a 2D List?
  • Summary of Summing a 2D Array in Python

What is a 2D Array or List in Python?

In many other languages, such as Java, you’d need to declare a 2D array type before assigning it. In Python, we can just make a list and make each entry in the list another list. A 2D array represents a two-dimensional space. These are sometimes referred to as “nested” lists. In our example, we’ll create a list of three lists, each consisting of two numbers. The below code shows how we can instantiate a simple 2D list in Python.

example_2d = [[1, 2], [3, 4], [5, 6]]

How Do You Sum an Array in Python?

There are multiple ways to sum a list in Python. We can do it iteratively, we can break the list down, or we can use the built-in sum() method. In this post, we’re going to sum a list the simplest way, by using the sum() method. In the example below we create a one-dimensional list of three numbers and then sum them.

example_1d =[1, 2, 3]
print(sum(example_1d))

This should output 6.

How Do You Sum a 2D List in Python?

Summing a 2D list or array object in Python is much more difficult. You can’t call the sum() function on a 2D array. If you try, you will get a TypeError of  unsupported operand type(s) for +: 'int' and 'list'. So, how can we sum a 2D array in Python? I’ll go over three examples here, first an iterative example, and then two Pythonic one liners.

Sum the 2D List with a For Loop

Summing a 2D array with a for loop is the most straightforward approach, especially for people new to Python. This is also the most intuitive approach for people coming from other programming languages. We start off with a sum of 0, notice that I named this variable _sum because the word sum is the name of the function. Then, we loop through each entry in the 2D list and add the sum() of that entry to our _sum variable. Finally, we print out our _sum variable to make sure that we got it.

_sum=0
for x in example_2d:
    _sum += sum(x)
print(_sum)

This should print 21.

Pythonically Sum The 2D Array in One Line

Now let’s take a look at the first “Pythonic” way of summing a 2D array. We can do this in one line. The most “inner” function of our line will use list comprehension and create a list from the sums of each entry in the 2D list. Then, we’ll call sum() on that and print it out. 

The inner list should be [3, 7, 11]. The printed answer should once again be 21.

print(sum([sum(x) for x in example_2d]))

Pythonically Sum the 2D List in One Line (More Obscure)

Finally, let’s take a look at another Pythonic way to sum a 2D array. We can take advantage of the sum() function’s optional second parameter. Usually, sum() expects to be summing numbers, so if you just call sum() on a 2D list, you’ll get a TypeError as we saw earlier. However, the optional second start parameter allows us to bypass this. If we pass an empty list object, it will expect the individual entries of the 2D array to be list objects like they are. This allows us to then call sum() again on the list and sum a 1D array.

The output of sum(example_2d, []) is [1, 2, 3, 4, 5, 6] just as if we added the lists together. The print statement prints 21.

print(sum(sum(example_2d, [])))

Summary of How to Sum a 2D List or Array

In this post we went over what a 2D list is and how you can sum arrays in Python. We also went over three separate methods to sum 2D lists. First, we went over an iterative method using for loops. Then, we went over a classic Pythonic method. Finally, we went over a more obscure approach using the optional start parameter of the sum() function.

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Make a one-time donation

Your contribution is appreciated.

Donate


Make a monthly donation

Your contribution is appreciated.

Donate monthly


Make a yearly donation

Your contribution is appreciated.

Donate yearly

Yujian Tang

На уроке рассматриваются алгоритмы работы с двумерными массивами в Python: создание матрицы, инициализация элементов, вывод, обработка элементов матрицы

Создание, вывод и ввод матрицы в Питоне

    Для работы с матрицами в Python также используются списки. Каждый элемент списка-матрицы содержит вложенный список.

  • Таким образом, получается структура из вложенных списков, количество которых определяет количество строк матрицы, а число элементов внутри каждого вложенного списка указывает на количество столбцов в исходной матрице.
  • Рассмотрим пример матрицы размера 4 х 3:

    matrix = [[-1, 0, 1], 
        [-1, 0, 1], 
        [0, 1, -1],
        [1, 1, -1]]

    Данный оператор можно записать в одну строку:

    matrix = [[-1, 0, 1], [-1, 0, 1], [0, 1, -1], [1, 1, -1]]
  • Вывод матрицы можно осуществить одним оператором, но такой простой способ не позволяет выполнять какой-то предварительной обработки элементов:

Результат:
 

вывод матрицы

  • Для вывода матрицы в виде таблицы можно использовать специально заготовленную для этого процедуру:
    1. способ:
    2. 1
      2
      3
      4
      5
      
      def printMatrix ( matrix ): 
         for i in range ( len(matrix) ): 
            for j in range ( len(matrix[i]) ): 
                print ( "{:4d}".format(matrix[i][j]), end = "" ) 
            print ()

      В примере i – это номер строки, а j – номер столбца;
      len(matrix) – число строк в матрице.

    3. способ:
    4. 1
      2
      3
      4
      5
      
      def printMatrix ( matrix ): 
         for row in matrix: 
            for x in row: 
                print ( "{:4d}".format(x), end = "" ) 
            print ()

      Внешний цикл проходит по строкам матрицы (row), а внутренний цикл проходит по элементам каждой строки (x).

  • Для инициализации элементов матрицы случайными числами используется алгоритм:
  • 1
    2
    3
    4
    
    from random import randint
    n, m = 3, 3
    a = [[randint(1, 10) for j in range(m)] for i in range(n)]
    print(a)

    Обработка элементов двумерного массива

    Нумерация элементов двумерного массива, как и элементов одномерного массива, начинается с нуля.
    Т.е. matrix[2][3] — это элемент третьей строки четвертого столбца.

    Пример обработки элементов матрицы:
    Найти произведение элементов двумерного массива.

    ✍ Решение:
     

    1
    2
    3
    4
    5
    
    p = 1 
    for i in range(N): 
        for j in range(M): 
           p *= matrix[i][j] 
    print (p)

    Пример:
    Найти сумму элементов двумерного массива.

    ✍ Решение:
     

    Более подходящий вариант для Python:

    1
    2
    3
    4
    
    s = 0 
    for row in matrix: 
       s += sum(row) 
    print (s)

    Для поиска суммы существует стандартная функция sum.

    Задание Python 8_0:
    Получены значения температуры воздуха за 4 дня с трех метеостанций, расположенных в разных регионах страны:

    Номер станции 1-й день 2-й день 3-й день 4-й день
    1 -8 -14 -19 -18
    2 25 28 26 20
    3 11 18 20 25

    Т.е. запись показаний в двумерном массиве выглядела бы так:

    t[0][0]=-8 t[0][1]=-14 t[0][2]=-19 t[0][3]=-18
    t[1][0]=25 t[1][1]=28 t[1][2]=26 t[1][3]=20
    t[2][0]=11 t[2][1]=18 t[2][2]=20 t[2][3]=25
    1. Распечатать температуру на 2-й метеостанции за 4-й день и на 3-й метеостанции за 1-й день.
    2. Распечатать показания термометров всех метеостанций за 2-й день.
    3. Определить среднюю температуру на 3-й метеостанции.
    4. Распечатать, в какие дни и на каких метеостанциях температура была в диапазоне 24-26 градусов тепла.

    Задание Python 8_1:
    Написать программу поиска минимального и максимального элементов матрицы и их индексов.

    Задание Python 8_2:
    Написать программу, выводящую на экран строку матрицы, сумма элементов которой максимальна.

  • Для обработки элементов квадратной матрицы (размером N x N):
  • Для элементов главной диагонали достаточно использовать один цикл:
  • for i in range(N): 
       # работаем с matrix[i][i]
  • Для элементов побочной диагонали:
  • for i in range(N): 
       # работаем с matrix[i][N-1-i]

    Пример:Переставить 2-й и 4-й столбцы матрицы. Использовать два способа.

    ✍ Решение:
     

    1. for i in range(N): 
        c = A[i][2] 
        A[i][2] = A[i][4] 
        A[i][4] = c
    2. for i in range(N): 
        A[i][2], A[i][4] = A[i][4], A[i][2]

    Задание Python 8_3:
    Составить программу, позволяющую с помощью датчика случайных чисел сформировать матрицу размерностью N. Определить:

  • минимальный элемент, лежащий ниже побочной диагонали;
  • произведение ненулевых элементов последней строки.
  • Improve Article

    Save Article

    Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given a 2-D matrix, we need to find sum of all elements present in matrix ? Examples:

    Input  : arr = [[1, 2, 3], 
                    [4, 5, 6], 
                    [2, 1, 2]]
    Output : Sum = 26

    This problem can be solved easily using two for loops by iterating whole matrix but we can solve this problem quickly in python using map() function. 

    Python3

    def findSum(arr):

        return sum(map(sum,arr))

    if __name__ == "__main__":

        arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]]

        print ("Sum = ",findSum(arr))

    What does map() do? 
    The map() function applies a given function to each item of an iterable(list, tuple etc.) and returns a list of the results. For example see given below example : 

    Python3

    def calculateSquare(n):

        return n*n

    numbers = [1, 2, 3, 4]

    result = map(calculateSquare, numbers)

    print (result)

    set_result=list(result)

    print(set_result)

    Output

    <map object at 0x7fdf95d2a6d8>
    [1, 4, 9, 16]
    

    This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Last Updated :
    21 Jul, 2022

    Like Article

    Save Article

    Матрица — это двухмерная структура данных, в которой числа расположены в виде строк и столбцов. Например:

    Эта матрица является матрицей три на четыре, потому что она состоит из 3 строк и 4 столбцов.

    • Матрицы в Python
    • NumPy массивы в Python
    • Как создать массив NumPy?
      • Массив целых чисел, чисел с плавающей точкой и составных чисел
      • Массив нулей и единиц
      • Использование arange() и shape()
    • Операции с матрицами
      • Сложение двух матриц или сумма элементов массива Python
      • Умножение двух матриц Python
      • Транспонирование матрицы питон
    • Доступ к элементам матрицы, строкам и столбца
      • Доступ к элементам матрицы
      • Доступ к строкам матрицы
      • Доступ к столбцам матрицы
    • Разделение матрицы

    Python не имеет встроенного типа данных для матриц. Но можно рассматривать список как матрицу. Например:

    A = [[1, 4, 5], 
        [-5, 8, 9]]
    

    Этот список является матрицей на 2 строки и 3 столбца.

    Матрицы в Python

    Обязательно ознакомьтесь с документацией по спискам Python, прежде чем продолжить читать эту статью.

    Давайте посмотрим, как работать с вложенным списком.

    A = [[1, 4, 5, 12], 
        [-5, 8, 9, 0],
        [-6, 7, 11, 19]]
    
    print("A =", A) 
    print("A[1] =", A[1])      # вторая строка
    print("A[1][2] =", A[1][2])   # третий элемент второй строки
    print("A[0][-1] =", A[0][-1])   # последний элемент первой строки
    
    column = [];        # пустой список
    for row in A:
      column.append(row[2])   
    
    print("3rd column =", column)
    

    Когда мы запустим эту программу, результат будет следующий:

    A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]
    A [1] = [-5, 8, 9, 0]
    A [1] [2] = 9
    A [0] [- 1] = 12
    3-й столбец = [5, 9, 11]
    

    Использование вложенных списков в качестве матрицы подходит для простых вычислительных задач. Но в Python есть более эффективный способ работы с матрицами – NumPy .

    NumPy — это расширение для научных вычислений, которое поддерживает мощный объект N-мерного массива. Прежде чем использовать NumPy, необходимо установить его. Для получения дополнительной информации,

    • Ознакомьтесь: Как установить NumPy Python?
    • Если вы работаете в Windows, скачайте и установите дистрибутив anaconda Python. Он поставляется вместе с NumPy и другими расширениями.

    После установки NumPy можно импортировать и использовать его.

    NumPy предоставляет собой многомерный массив чисел (который на самом деле является объектом). Давайте рассмотрим приведенный ниже пример:

    import numpy as np
    a = np.array([1, 2, 3])
    print(a)               # Вывод: [1, 2, 3]
    print(type(a))         # Вывод: <class 'numpy.ndarray'>
    

    Как видите, класс массива NumPy называется ndarray.

    Существует несколько способов создания массивов NumPy.

    import numpy as np
    
    A = np.array([[1, 2, 3], [3, 4, 5]])
    print(A)
    
    A = np.array([[1.1, 2, 3], [3, 4, 5]]) # Массив чисел с плавающей запятой
    print(A)
    
    A = np.array([[1, 2, 3], [3, 4, 5]], dtype = complex) # Массив составных чисел
    print(A)
    

    Когда вы запустите эту программу, результат будет следующий:

    [[1 2 3]
     [3 4 5]]
    
    [[1.1 2. 3.]
     [3. 4. 5.]]
    
    [[1. + 0.j 2. + 0.j 3. + 0.j]
     [3. + 0.j 4. + 0.j 5. + 0.j]]
    
    
    import numpy as np
    
    zeors_array = np.zeros( (2, 3) )
    print(zeors_array)
    
    '''
     Вывод:
     [[0. 0. 0.]
      [0. 0. 0.]]
    '''
    
    ones_array = np.ones( (1, 5), dtype=np.int32 ) // указание dtype
    print(ones_array)      # Вывод: [[1 1 1 1 1]]
    

    Здесь мы указали dtype — 32 бита (4 байта). Следовательно, этот массив может принимать значения от -2-31 до 2-31-1.

    import numpy as np
    
    A = np.arange(4)
    print('A =', A)
    
    B = np.arange(12).reshape(2, 6)
    print('B =', B)
    
    ''' 
    Вывод:
    A = [0 1 2 3]
    B = [[ 0  1  2  3  4  5]
     [ 6  7  8  9 10 11]]
    '''
    

    Узнайте больше о других способах создания массива NumPy .

    Выше мы привели пример сложение, умножение матриц и транспонирование матрицы. Мы использовали вложенные списки, прежде чем создавать эти программы. Рассмотрим, как выполнить ту же задачу, используя массив NumPy.

    Мы используем оператор +, чтобы сложить соответствующие элементы двух матриц NumPy.

    import numpy as np
    
    A = np.array([[2, 4], [5, -6]])
    B = np.array([[9, -3], [3, 6]])
    C = A + B      # сложение соответствующих элементов
    print(C)
    
    ''' 
    Вывод:
    [[11  1]
     [ 8  0]]
     '''
    

    Чтобы умножить две матрицы, мы используем метод dot(). Узнайте больше о том, как работает numpy.dot .

    Примечание: * используется для умножения массива (умножения соответствующих элементов двух массивов), а не умножения матрицы.

    import numpy as np
    
    A = np.array([[3, 6, 7], [5, -3, 0]])
    B = np.array([[1, 1], [2, 1], [3, -3]])
    C = a.dot(B)
    print(C)
    
    ''' 
    Вывод:
    [[ 36 -12]
     [ -1   2]]
    '''
    

    Мы используем numpy.transpose для вычисления транспонирования матрицы.

    import numpy as np
    
    A = np.array([[1, 1], [2, 1], [3, -3]])
    print(A.transpose())
    
    ''' 
    Вывод:
    [[ 1  2  3]
     [ 1  1 -3]]
    '''
    

    Как видите, NumPy значительно упростил нашу задачу.

    Также можно получить доступ к элементам матрицы, используя индекс. Начнем с одномерного массива NumPy.

    import numpy as np
    A = np.array([2, 4, 6, 8, 10])
    
    print("A[0] =", A[0])     # Первый элемент     
    print("A[2] =", A[2])     # Третий элемент     
    print("A[-1] =", A[-1])   # Последний элемент     
    

    Когда вы запустите эту программу, результат будет следующий:

    A [0] = 2
    A [2] = 6
    A [-1] = 10
    

    Теперь выясним, как получить доступ к элементам двухмерного массива (который в основном представляет собой матрицу).

    import numpy as np
    
    A = np.array([[1, 4, 5, 12],
        [-5, 8, 9, 0],
        [-6, 7, 11, 19]])
    
    #  Первый элемент первой строки
    print("A[0][0] =", A[0][0])  
    
    # Третий элемент второй строки
    print("A[1][2] =", A[1][2])
    
    # Последний элемент последней строки
    print("A[-1][-1] =", A[-1][-1])     
    

    Когда мы запустим эту программу, результат будет следующий:

    A [0] [0] = 1
    A [1] [2] = 9
    A [-1] [- 1] = 19
    
    import numpy as np
    
    A = np.array([[1, 4, 5, 12], 
        [-5, 8, 9, 0],
        [-6, 7, 11, 19]])
    
    print("A[0] =", A[0]) # Первая строка
    print("A[2] =", A[2]) # Третья строка
    print("A[-1] =", A[-1]) # Последняя строка (третья строка в данном случае)
    

    Когда мы запустим эту программу, результат будет следующий:

    A [0] = [1, 4, 5, 12]
    A [2] = [-6, 7, 11, 19]
    A [-1] = [-6, 7, 11, 19]
    
    import numpy as np
    
    A = np.array([[1, 4, 5, 12], 
        [-5, 8, 9, 0],
        [-6, 7, 11, 19]])
    
    print("A[:,0] =",A[:,0]) # Первый столбец
    print("A[:,3] =", A[:,3]) # Четвертый столбец
    print("A[:,-1] =", A[:,-1]) # Последний столбец (четвертый столбец в данном случае)
    

    Когда мы запустим эту программу, результат будет следующий:

    A [:, 0] = [1 -5 -6]
    A [:, 3] = [12 0 19]
    A [:, - 1] = [12 0 19]
    

    Если вы не знаете, как работает приведенный выше код, прочтите раздел «Разделение матрицы».

    Разделение одномерного массива NumPy аналогично разделению списка. Рассмотрим пример:

    import numpy as np
    letters = np.array([1, 3, 5, 7, 9, 7, 5])
    
    # с 3-го по 5-ый элементы
    print(letters[2:5])        # Вывод: [5, 7, 9]
    
    # с 1-го по 4-ый элементы
    print(letters[:-5])        # Вывод: [1, 3]   
    
    # с 6-го до последнего элемента
    print(letters[5:])         # Вывод:[7, 5]
    
    # с 1-го до последнего элемента
    print(letters[:])          # Вывод:[1, 3, 5, 7, 9, 7, 5]
    
    # список в обратном порядке
    print(letters[::-1])          # Вывод:[5, 7, 9, 7, 5, 3, 1]
    

    Теперь посмотрим, как разделить матрицу.

    import numpy as np
    
    A = np.array([[1, 4, 5, 12, 14], 
        [-5, 8, 9, 0, 17],
        [-6, 7, 11, 19, 21]])
    
    print(A[:2, :4])  # две строки, четыре столбца
    
    ''' Вывод:
    [[ 1  4  5 12]
     [-5  8  9  0]]
    '''
    
    print(A[:1,])  # первая строка, все столбцы
    
    ''' Вывод:
    [[ 1  4  5 12 14]]
    '''
    
    print(A[:,2])  # все строки, второй столбец
    
    ''' Вывод:
    [ 5  9 11]
    '''
    
    print(A[:, 2:5])  # все строки, с третьего по пятый столбец
    ''' Вывод:
    [[ 5 12 14]
     [ 9  0 17]
     [11 19 21]]
    '''
    

    Использование NumPy вместо вложенных списков значительно упрощает работу с матрицами. Мы рекомендуем детально изучить пакет NumPy, если вы планируете использовать Python для анализа данных.

    Понравилась статья? Поделить с друзьями:
  • Как найти среднесписочную численность рабочих за месяц
  • Как найти результаты пцр теста на госуслугах
  • Надписи как найти подарок
  • Как найти внутреннюю гармонию книги
  • Как найти мамины очки