# Python之向量相加中使用到list元素求和、合并

## 一、问题描述

Python的向量运算可以使用Python运算逻辑实现，也可以用numpy包实现，这里通过编写相关代码进行演示，同时指出list列表的元素求和、合并的表达

## 二、向量相加的两种方法

# 向量相加-Python
def pythonsum(n):
a = list(range(n))
b = list(range(n))
c = []
for i in range(len(a)):
a[i] = i ** 2
b[i] = i ** 3
c.append(a[i] + b[i])
return c

# 向量相加-NumPy
import numpy as np

def numpysum(n):
a = np.arange(n) ** 2
b = np.arange(n) ** 3
c = list(a + b)
return c

print("Python sum list is", pythonsum(10))
print("numpy sum list is", numpysum(10))


# 效率比较
import sys
from datetime import datetime

size = 100000

start = datetime.now()
c = pythonsum(size)
delta = datetime.now() - start
print("The last 2 elements of the sum", c[-2:])
print("PythonSum elapsed time in microseconds", delta.microseconds)

start = datetime.now()
c = numpysum(size)
delta = datetime.now() - start
print("The last 2 elements of the sum", c[-2:])
print("NumPySum elapsed time in microseconds", delta.microseconds)


## 三、示例中list求和及延伸

1.Python中a[i] + b[i]

a = [1, 2]
b = [3, 4]
c = []
for i in range(len(a)):
c.append(a[i] + b[i])
print(c)


2.numpy中list(a + b)

import numpy as np

a = np.array([1, 2])
b = np.array([3, 4])
c = list(a + b)
print(c)


3.延伸
（1）合并，如果表达为a+b，则两个列表将合并

a = [1, 2]
b = [3, 4]
c = a + b
print(c)


（2）numpy的sum求和

import numpy as np

a = [1, 2]
b = [3, 4]
c = list(np.sum([a, b], axis = 0))
print(c)


09-28 2623
06-08 15万+
02-20 1万+
07-15 7万+
01-07 31万+
03-16
04-15 959
08-26 152
10-22 1608