在Python中,计算两个列表中对应元素相加可以通过多种方法实现,以下是几种常见的方法:
1. 使用`zip`函数和列表推导式:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [x + y for x, y in zip(list1, list2)]
print(result) 输出:[5, 7, 9]
2. 使用`map`函数和`operator.add`:
```python
from operator import add
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(map(add, list1, list2))
print(result) 输出:[5, 7, 9]
3. 使用`for`循环遍历列表:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = []
for i in range(len(list1)):
result.append(list1[i] + list2[i])
print(result) 输出:[5, 7, 9]
4. 使用`sum`函数和`zip`函数:
```python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = [sum(pair) for pair in zip(list1, list2)]
print(result) 输出:[5, 7, 9]