Как сложить элементы двух списков?
Если важно сохранить начальные списки, то попробуем по другому:
# заполнение переменных a = [1, 2, 3, 4] b = [1, 2, 3] # обработка c = map(sum, zip(a + [0,]*(len(b)-len(a)), b + [0,]*(len(a)-len(b)))) # вывод результата print(list(c))
Вариант 3:
В Python 3.8 появился «морж» — оператор := Если важно не повторить функционал:
# заполнение переменных a = [1, 2, 3, 4] b = [1, 2, 3] # обработка c = map(sum, zip(a + [0, ] * (x := len(b) - len(a)), b + [0, ] * -x)) # вывод результата print(list(c)) Результат: > [2, 4, 6, 4]
Если вы еще не «прошли ‘from’ ‘import'», то наиболее простой вариант выглядит вот так:
с=list(map(lambda x, y: x + y, a, b))
c1 = [x+y for x,y in zip(a,b)] + (a if len(a) >= len(b) else b)[min(len(a), len(b)):]
При необходимости обернуть это в вызов функции, надеюсь, сможете сделать самостоятельно: на вход a и b, указанные выражения — в качестве параметра в return.
Спасибо тебе за ответ) мне нужно просто без комприхенш`на может просто через def и внутри def через for буду рад если поможете = )
Если у вас списка ВСЕГДА точно будут одной длины, то можно воспользоваться генератор списков и zip:
a = [1, 2, 3] b = [4, 5, 6] c = [x+y for x, y in zip(a, b)] print(c) #[5, 7, 9]
Но если вы НЕ уверены, что длина списков будет одинаковой хоть раз, то здесь нужно воспользоваться крутой библиотекой itertools:
from itertools import zip_longest a = [1, 2, 3] b = [4, 5, 6, 10] c = [x+y for x, y in zip_longest(a, b, fillvalue=0) #fillvalue нужен, если ваши списки разных рамеров и там где не достаёт элементов, добьёт нулями. print(c) #[5, 7, 9, 10]
from itertools import zip_longest def add_list(a, b): c = [x+y for x, y in zip_longest(a, b, fillvalue=0)] return c a = [1, 2, 3] b = [4, 5, 6, 10] summ_list = add_list(a, b) print(summ_list)
Find sum of two lists in Python
In this article, we will discuss different ways to get the sum of two lists element wise and store that to a new list in Python.
Table Of Contents
Introduction
Suppose we have two lists,
firstList = [21, 23, 13, 44, 11, 19] secondList = [49, 48, 47, 46, 45, 44]
Now we want to add these two lists element wise and store the result in an another list. Contents of this merged list will be,
In the above example, nth item of first list should be added to the nth item of second list, and summed up values should be added to a new list. There are different ways to do this. Let’s discuss them one by one,
Frequently Asked:
Find sum of two lists using zip() and List Comprehension
Pass both the lists to zip() function as arguments. It will return a zipped object, which yields tuples, containing an item from both the lists, until an any one list is exhaused. We can add the items in each of the returned tuple and store the result in a new list. In the end we will get a list containing the sum of two lists element wise. For example,
firstList = [21, 23, 13, 44, 11, 19] secondList = [49, 48, 47, 46, 45, 44] # get the sum of two lists element wise mergedList = [sum(x) for x in zip(firstList, secondList)] print(mergedList)
We added both the lists element wise.
Find sum of two lists using for loop
Create a new empty list. Then, select the smallest list out of the two given lists. Get the size of that smallest list. Iterate from 0 till the size of smallest list. In each ith iteration of for loop, get the sum of values at ith index in both the list and store that at ith position in new list. For example,
firstList = [21, 23, 13, 44, 11, 19] secondList = [49, 48, 47, 46, 45, 44] size = min(len(firstList), len(secondList)) # get the sum of two lists element wise mergedList = [] for i in range(size): value = firstList[i] + secondList[i] mergedList.append(value) print(mergedList)
We added both the lists element wise.
Summary
We learned how to get the sum of two lists in Python. Thanks.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.