Сложение элементов массива питон

Python Sum of List How to Sum Elements of Two Lists in Python

Welcome back to another edition of the How to Python series. This time I want to sum elements of two lists in Python. I got the inspiration for this topic while trying to do just this at work, so let’s see how it goes!

Problem Introduction

Recently, I ran into a problem where a library wasn’t working exactly how I wanted, so I had to hack together the results to make my life a bit easier. In this scenario, I had a connection library which I was using to list all the available devices. However, the list functionality short circuited for certain types of connections, so it never actually listed everything. As a result, I was forced to run the function twice: once for USB and again for Ethernet. The results of this list function returned a list that looked something like the following:

# [size, [types], [interfaces], [serial numbers], [IP addresses]] [2, [7, 7], [1, 2], [2314567, 8374163], [0, 84302738]] 
[1, [7], [2], [8374163], [84302738]] # Ethernet [1, [7], [1], [2314567], [0]] # USB 

Naturally, I wanted to be able to merge the two lists back into what I was expecting initially. However, I wasn’t totally sure how I was going to do that. So, let’s take a look at some possible solutions.

Читайте также:  Use sql database in java

Solutions

Merge Two Lists by Hand

ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] all_devices = [ ethernet_devices[0] + usb_devices[0], ethernet_devices[1] + usb_devices[1], ethernet_devices[2] + usb_devices[2], ethernet_devices[3] + usb_devices[3], ethernet_devices[4] + usb_devices[4] ] 

Now, that solution is hardly elegant, but it gets the job done. However, there has to be a better way. After all, we are already taking advantage of the fact that lists can be merged using the same operator as addition. Why not take advantage of this property in a loop?

Sum Elements of Two Lists with a Comprehension

Just like the last lesson on inverting dictionaries in Python, we can take advantage of comprehensions to dramatically simplify this problem. Let’s take a look:

ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)] 

Now we’re talking! That’s five lines of tedious mapping compressed down into a simple list comprehension. But wait, it gets better:

all_devices = [sum(pair) for pair in zip(ethernet_devices, usb_devices)] 

Or, does it? Thanks to our fried, rhymes, we’ll notice that this solution doesn’t actually work for our situation. While it does a great job summing integers in an iterable, it crashes when trying to merge two sublists with the following error:

Traceback (most recent call last): File "", line 1, in all_devices = [sum(pair) for pair in zip(ethernet_devices, usb_devices)] File "", line 1, in all_devices = [sum(pair) for pair in zip(ethernet_devices, usb_devices)] TypeError: unsupported operand type(s) for +: 'int' and 'list' 

Sum Elements of Two Lists with a Mapping

At this point, we’ve basically answered our question. However, there is another solution which requires arguably even less code. Check it out:

ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] import operator all_devices = list(map(operator.add, ethernet_devices, usb_devices)) 

Not totally certain of the performance impact here, but it sure is a pretty solution. Of course, we also need to add a dependency which does make this solution a bit less attractive. In fact, if we were going to go down that road, we could easily leverage numpy:

ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] import numpy as np all_devices = np.add(ethernet_devices, usb_devices) 

A Little Recap

ethernet_devices = [1, [7], [2], [8374163], [84302738]] usb_devices = [1, [7], [1], [2314567], [0]] # The long way all_devices = [ ethernet_devices[0] + usb_devices[0], ethernet_devices[1] + usb_devices[1], ethernet_devices[2] + usb_devices[2], ethernet_devices[3] + usb_devices[3], ethernet_devices[4] + usb_devices[4] ] # Some comprehension magic all_devices = [x + y for x, y in zip(ethernet_devices, usb_devices)] # Let's use maps import operator all_devices = list(map(operator.add, ethernet_devices, usb_devices)) # We can't forget our favorite computation library import numpy as np all_devices = np.add(ethernet_devices, usb_devices) 

As we can see, there are a lot of ways to run an element-wise sum of two lists. Take your pick. As always, thanks for stopping by! If you’re interested in learning more about Python, consider subscribing to The Renegade Coder, so you’ll never miss another article.

Источник

Как найти сумму чисел в списке Python

Обложка для статьи

Python — это язык программирования, который предоставляет нам различные встроенные функции и методы для работы со списками. Одной из таких операций является нахождение суммы чисел в списке. Это может быть полезным, когда необходимо произвести анализ числовых данных, например, при подсчете среднего значения или нахождении суммы элементов, удовлетворяющих определенным условиям. В этой статье мы рассмотрим различные методы нахождения суммы чисел в списке Python.

Методы для нахождения суммы чисел в списке

Использование цикла for

Цикл for является одним из наиболее простых и часто используемых способов для нахождения суммы чисел в списке. Просто пройдитесь по каждому элементу списка и добавьте его к накопленной сумме.

Вот пример кода, который демонстрирует использование цикла for для нахождения суммы чисел в списке:

numbers = [1, 2, 3, 4, 5] total = 0 for num in numbers: total += num print("Сумма чисел в списке: ", total)

В этом примере мы создали список чисел от 1 до 5 и присвоили его переменной numbers . Затем мы создали переменную total и присвоили ей начальное значение 0. Затем мы проходим по каждому элементу списка numbers и добавляем его к переменной total . Наконец, мы выводим сумму чисел на экран.

Важно отметить, что мы должны инициализировать переменную total нулевым значением перед выполнением цикла, чтобы иметь место, куда добавлять числа. Если мы попытаемся добавить число к неинициализированной переменной, возникнет ошибка.

Цикл for также может использоваться для нахождения суммы чисел в многомерном списке. В этом случае нам нужно будет использовать вложенный цикл for , чтобы перебрать каждый элемент списка.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] total = 0 for row in matrix: for num in row: total += num print("Сумма чисел в многомерном списке: ", total)

В этом примере мы создали многомерный список, содержащий три списка с числами. Затем мы создали переменную total и присвоили ей начальное значение 0. Затем мы используем два вложенных цикла for для перебора каждого элемента списка и добавления его к переменной total . Наконец, мы выводим сумму чисел на экран.

Использование встроенной функции sum()

Использование встроенной функции sum() для нахождения суммы чисел в списке является очень простым и эффективным способом. Функция sum() принимает один аргумент — итерируемый объект, такой как список, и возвращает сумму всех элементов в нем.

Простой пример использования функции sum() для нахождения суммы всех чисел в списке:

my_list = [1, 2, 3, 4, 5] sum_of_list = sum(my_list) print(sum_of_list)

Важно отметить, что функция sum() может работать только с итерируемыми объектами, элементы которых могут быть сложены. Если элементы списка не могут быть сложены, будет возбуждено исключение типа TypeError .

Использование рекурсии

Использование рекурсии — это еще один способ нахождения суммы чисел в списке Python. Рекурсия — это процесс вызова функцией самой себя. Для нахождения суммы чисел в списке при помощи рекурсии, необходимо реализовать функцию, которая будет вызывать саму себя до тех пор, пока не достигнет базового случая.

Пример реализации функции для нахождения суммы чисел в списке при помощи рекурсии:

numbers = [1, 2, 3, 4, 5] result = recursive_sum(numbers) print(result)

Здесь мы определяем функцию recursive_sum , которая принимает список чисел numbers . Если в списке остается только один элемент, то возвращаем его значение. В противном случае мы возвращаем сумму первого элемента списка и рекурсивного вызова функции для оставшейся части списка.

Хотя использование рекурсии для нахождения суммы чисел в списке может быть удобным и понятным, стоит иметь в виду, что это может привести к переполнению стека вызовов функций при больших списках. Поэтому, в большинстве случаев лучше использовать более эффективные методы, такие как использование встроенной функции sum() или цикла for .

Обработка исключений при нахождении суммы чисел в списке

При работе с данными, особенно с пользовательским вводом, всегда есть вероятность получения ошибочных данных. Для обработки ошибок при нахождении суммы чисел в списке можно использовать конструкцию try-except.

При использовании описанных выше методов для нахождения суммы чисел в списке возможны следующие ошибки:

  1. TypeError — возникает, если элемент списка не является числом.
  2. ValueError — возникает, если в списке есть пустые строки или нечисловые значения.

Для обработки этих ошибок можно использовать конструкцию try-except. Например, чтобы обработать ошибку TypeError, мы можем использовать следующий код:

numbers = [1, 2, 3, '4', 5] total = 0 for num in numbers: try: total += num except TypeError: print(f"Элемент не является числом") print(f"Сумма чисел в списке: ")

В результате выполнения данного кода мы получим следующий вывод:

Элемент 4 не является числом Сумма чисел в списке: 11

Обработка ошибок позволяет избежать прерывания работы программы при возникновении ошибок и предоставляет возможность корректно обработать их в процессе выполнения программы.

Источник

Sum of Elements in a List in Python

Lists are very commonly used to store sequences of values (for example, numbers) in Python. When working with lists, it can be handy to know how to quickly get the sum of values in a list. For example, you have a list of your recorded footsteps in the last seven days and you want to know the total sum. In this tutorial, we will look at how to get the sum of the elements in a list in Python with the help of some examples.

How to get the sum of a list of numbers in Python?

sum of elements in a python list

You can use the python built-in sum() function to get the sum of list elements. Alternatively, you can use a loop to iterate through the list items and use a variable to keep track of the sum.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Let’s look at the above-mentioned methods with the help of some examples.

Using sum() to get the total in a list

The built-in sum() function in Python is used to return the sum of an iterable. To get the sum total of a list of numbers, you can pass the list as an argument to the sum() function.

# create a list ls = [10, 15, 20, 25] # sum of list elements sum(ls)

We get the sum of the values in the list as a scaler value.

Note that the sum() function may result in loss of precision with extended sums of floating-point numbers. For example –

# create a list ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] # sum of list elements sum(ls)

As an alternative, you can use the math standard library’s fsum() function to get an accurate sum of floating-point numbers and prevent loss of precision.

import math # create a list ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] # sum of list elements math.fsum(ls)

We get the accurate result this time. For more on the fsum() function, refer to its documentation.

Using loop to get the sum

Alternatively, you can use the straightforward method of iterating through the list elements and keeping track of the sum.

# create a list ls = [10, 15, 20, 25] # use a loop to get the sum total = 0 for item in ls: total += item print(total)

We get the sum of the values in the list.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью