programing

두 LIST의 값 합계를 새 LIST에 추가

telebox 2023. 5. 2. 22:36
반응형

두 LIST의 값 합계를 새 LIST에 추가

다음 두 가지 목록이 있습니다.

first = [1,2,3,4,5]
second = [6,7,8,9,10]

이제 이 두 목록의 항목을 새 목록에 추가하려고 합니다.

출력은 다음과 같아야 합니다.

third = [7,9,11,13,15]

zip함수는 여기서 유용하며, 목록 이해와 함께 사용됩니다.

[x + y for x, y in zip(first, second)]

목록이 있는 경우(단 두 개의 목록이 아닌):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

문서에서

import operator
list(map(operator.add, first,second))

의 기본 동작numpy.add(numpy.subtract등)는 요소별입니다.

import numpy as np
np.add(first, second)

어떤 결과물이 나오는지

array([7,9,11,13,15])

두 목록 모두를 가정합니다.a그리고.b길이가 같고, 지퍼, 누피 또는 다른 것이 필요하지 않습니다.

Python 2.x 및 3.x:

[a[i]+b[i] for i in range(len(a))]

다음 코드를 사용해 보십시오.

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

이는 임의의 수의 목록으로 확장됩니다.

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

당신의 경우에는,myListOfLists되지요[first, second]

이를 위한 쉽고 빠른 방법은 다음과 같습니다.

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

또는 numpy sum을 사용할 수 있습니다.

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])

일직선 해법

list(map(lambda x,y: x+y, a,b))
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = list(map(sum, first, second))
print(three)



# Output 
[7, 9, 11, 13, 15]

길이가 같은 목록이 알 수 없는 경우 아래 기능을 사용할 수 있습니다.

여기서 *args는 다양한 수의 리스트 인수를 허용하지만 각 인수의 요소 수는 같습니다.*는 각 목록의 요소를 압축 해제하는 데 다시 사용됩니다.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

출력:

[2, 4, 6]

또는 3개의 목록과 함께

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

출력:

[19, 19, 19, 19, 19]

제 답변은 3월 17일 9시 25분에 답변한 티루의 답변과 반복됩니다.

그의 솔루션은 더 간단하고 빠릅니다.

이를 위한 쉽고 빠른 방법은 다음과 같습니다.

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

또는 numpy sum을 사용할 수 있습니다.

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

넌 멍청이가 필요해!

numpy array could do some operation like vectors

import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

길이가 다른 목록이 있으면 다음과 같은 작업을 수행할 수 있습니다(사용).zip_longest)

from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]

사용할 수 있습니다.zip()두 배열을 함께 "인터리브"할 것이고, 그리고 나서.map()반복 가능한 각 요소에 함수를 적용합니다.

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]

여기 다른 방법이 있습니다.우리는 파이썬의 내부 __add_ 함수를 사용합니다.

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

산출량

[11, 22, 33, 44, 55]

목록의 나머지 값도 추가하려면 이를 사용할 수 있습니다(이것은 Python 3.5에서 작동합니다).

def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum


#for testing 
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))
    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third) 
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]

여기 다른 방법이 있습니다.그것은 저에게 잘 작동하고 있습니다.

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")
j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]

목록을 numpy 배열로 간주할 경우 쉽게 요약해야 합니다.

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

아마도 가장 간단한 접근법:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)
first = [1,2,3,4,5]
second = [6,7,8,9,10]
third=[]
for i,j in zip(first,second):
    t=i+j
    third.append(t)
print("Third List=",third)

output -- Third List= [7, 9, 11, 13, 15]

이 방법을 사용할 수 있지만 두 목록의 크기가 동일한 경우에만 작동합니다.

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third

언급URL : https://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list

반응형